diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 7c1df387f5353..63cd425c71184 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -265,9 +265,6 @@ # PRLabel: %Communication - Common /sdk/communication/azure-communication-common/ @Azure/acs-identity-sdk @AikoBB @maximrytych-ms @mjafferi-msft -# PRLabel: %Communication - Network Traversal -/sdk/communication/azure-communication-networktraversal/ @ankitarorabit @minnieliu @Azure/azure-sdk-communication-code-reviewers - # PRLabel: %Communication - Phone Numbers /sdk/communication/azure-communication-phonenumbers/ @miguhern @whisper6284 @RoyHerrod @danielav7 @@ -399,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 @@ -433,7 +430,7 @@ # ServiceLabel: %Event Grid # AzureSdkOwners: @billwert -# ServiceOwners: @jfggdl +# ServiceOwners: @Kishp01 @ahamad-MS # PRLabel: %Event Hubs /sdk/eventhubs/ @conniey @anuchandy @lmolkova @@ -561,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 @@ -650,9 +647,6 @@ # ServiceLabel: %Redis Cache # ServiceOwners: @yegu-ms -# ServiceLabel: %Relay -# ServiceOwners: @jfggdl - # PRLabel: %Remote Rendering /sdk/remoterendering/ @MichaelZp0 @ChristopherManthei @@ -799,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 diff --git a/.github/CODEOWNERS_baseline_errors.txt b/.github/CODEOWNERS_baseline_errors.txt index e0dbd7daa065a..faf15e0ee1685 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/.github/workflows/event-processor.yml b/.github/workflows/event-processor.yml index 615c51b0f82e0..8f448d1d77937 100644 --- a/.github/workflows/event-processor.yml +++ b/.github/workflows/event-processor.yml @@ -58,7 +58,7 @@ jobs: run: > dotnet tool install Azure.Sdk.Tools.GitHubEventProcessor - --version 1.0.0-dev.20240311.2 + --version 1.0.0-dev.20240502.2 --add-source https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-net/nuget/v3/index.json --global shell: bash @@ -114,7 +114,7 @@ jobs: run: > dotnet tool install Azure.Sdk.Tools.GitHubEventProcessor - --version 1.0.0-dev.20240311.2 + --version 1.0.0-dev.20240502.2 --add-source https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-net/nuget/v3/index.json --global shell: bash diff --git a/.github/workflows/scheduled-event-processor.yml b/.github/workflows/scheduled-event-processor.yml index 120531ac3d5b3..09d530acfe985 100644 --- a/.github/workflows/scheduled-event-processor.yml +++ b/.github/workflows/scheduled-event-processor.yml @@ -39,7 +39,7 @@ jobs: run: > dotnet tool install Azure.Sdk.Tools.GitHubEventProcessor - --version 1.0.0-dev.20240311.2 + --version 1.0.0-dev.20240502.2 --add-source https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-net/nuget/v3/index.json --global shell: bash diff --git a/.vscode/cspell.json b/.vscode/cspell.json index d449ceee2cd9b..37c1ec06e30ca 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -454,7 +454,12 @@ "mylocation", "myloc", "dari", - "hitel" + "hitel", + "AISERVICES", + "AICLIP", + "TLARGE", + "TBASE", + "TGIANT" ] }, { diff --git a/common/perf-test-core/pom.xml b/common/perf-test-core/pom.xml index 8b7c9183d9657..4ea0c0b19b47f 100644 --- a/common/perf-test-core/pom.xml +++ b/common/perf-test-core/pom.xml @@ -82,22 +82,22 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 io.vertx diff --git a/common/smoke-tests/pom.xml b/common/smoke-tests/pom.xml index 7b7e582846f44..d8303d2dd9b2e 100644 --- a/common/smoke-tests/pom.xml +++ b/common/smoke-tests/pom.xml @@ -88,43 +88,43 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 com.azure azure-core-amqp - 2.9.3 + 2.9.4 com.azure azure-cosmos - 4.58.0 + 4.59.0 com.azure azure-identity - 1.12.0 + 1.12.1 diff --git a/eng/emitter-package-lock.json b/eng/emitter-package-lock.json index d74bddeb2891c..7d1f72e794290 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 15fe2aad5a8e5..d566172a15d67 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/generate_utils.py b/eng/mgmt/automation/generate_utils.py index 66b26979fd0de..8194eae9be2b6 100644 --- a/eng/mgmt/automation/generate_utils.py +++ b/eng/mgmt/automation/generate_utils.py @@ -11,6 +11,7 @@ import subprocess import urllib.parse from typing import Tuple, List, Union +from typespec_utils import validate_tspconfig pwd = os.getcwd() #os.chdir(os.path.abspath(os.path.dirname(sys.argv[0]))) @@ -77,7 +78,12 @@ def generate( ) logging.info(command) if os.system(command) != 0: - logging.error('[GENERATE] Autorest fail') + error_message = ('[GENERATE][Error] Code generation failed.\n' + 'Please first check if the failure happens only to Java automation, or for all SDK automations.\n' + 'If it happens for all SDK automations, please double check your Swagger, and check whether there is errors in ModelValidation and LintDiff.\n' + 'If it happens to Java alone, you can open an issue to https://github.com/Azure/autorest.java/issues. Please include the link of this Pull Request in the issue.') + logging.error(error_message) + print(error_message, file=sys.stderr) return False group = GROUP_ID @@ -93,7 +99,10 @@ def compile_package(sdk_root, module) -> 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: - logging.error('[COMPILE] Maven build fail') + error_message = ('[COMPILE] Maven build fail.\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 @@ -321,6 +330,8 @@ def generate_typespec_project( tsp_project, re.IGNORECASE ) + + tspconfig_valid = True if url_match: # generate from remote url cmd = ['npx', 'tsp-client', 'init', '--debug', @@ -328,20 +339,26 @@ def generate_typespec_project( else: # sdk automation tsp_dir = os.path.join(spec_root, tsp_project) if spec_root else tsp_project + tspconfig_valid = validate_tspconfig(tsp_dir) repo = remove_prefix(repo_url, 'https://github.com/') cmd = ['npx', 'tsp-client', 'init', '--debug', '--tsp-config', tsp_dir, '--commit', head_sha, '--repo', repo, '--local-spec-repo', tsp_dir] - check_call(cmd, sdk_root) - sdk_folder = find_sdk_folder(sdk_root) - logging.info('SDK folder: ' + sdk_folder) - if sdk_folder: - succeeded = True + if tspconfig_valid: + check_call(cmd, sdk_root) + + sdk_folder = find_sdk_folder(sdk_root) + logging.info('SDK folder: ' + sdk_folder) + if sdk_folder: + succeeded = True except subprocess.CalledProcessError as error: - logging.error(f'tsp-client init fail: {error}') + error_message = (f'[GENERATE][Error] Code generation failed. tsp-client init fails: {error}\n' + 'If TypeSpec Validation passes, you can open an issue to https://github.com/Azure/autorest.java/issues. Please include the link of this Pull Request in the issue.') + logging.error(error_message) + print(error_message, file=sys.stderr) if succeeded: # check require_sdk_integration diff --git a/eng/mgmt/automation/init.sh b/eng/mgmt/automation/init.sh index 8cc167905e1cb..5414fa94a5eac 100755 --- a/eng/mgmt/automation/init.sh +++ b/eng/mgmt/automation/init.sh @@ -7,7 +7,7 @@ pip3 install --upgrade PyYAML requests 2>&1 # install tsp-client globally (local install may interfere with tooling) echo Install tsp-client -npm install -g @azure-tools/typespec-client-generator-cli +npm install -g @azure-tools/typespec-client-generator-cli 2>&1 cat << EOF > $2 {"envs": {"PATH": "$JAVA_HOME_11_X64/bin:$PATH", "JAVA_HOME": "$JAVA_HOME_11_X64"}} diff --git a/eng/mgmt/automation/typespec_utils.py b/eng/mgmt/automation/typespec_utils.py new file mode 100644 index 0000000000000..215b291242673 --- /dev/null +++ b/eng/mgmt/automation/typespec_utils.py @@ -0,0 +1,81 @@ +import os +import re +import sys +import yaml +import logging + + +def validate_tspconfig(tsp_dir: str) -> bool: + """ + Validate that the "tspconfig.yaml" file is correctly configured for Java Azure lib. + Side effect, the function would log/print the error messages, if validation fails. + + :param tsp_dir: the path to the "tspconfig.yaml" file, or the directory contains the file. + :return: whether this "tspconfig.yaml" file is valid. + """ + + valid = True + + if not tsp_dir.endswith('tspconfig.yaml'): + tsp_dir = os.path.join(tsp_dir, 'tspconfig.yaml') + with open(tsp_dir, 'r') as tspconfig: + yaml_json = yaml.safe_load(tspconfig) + + service_dir_pattern = r'sdk/\w+' + package_dir_pattern = r'azure(-\w+)+' + namespace_pattern = r'com\.azure(\.\w+)+' + + # SDK automation would make sure these properties exists + service_dir: str = yaml_json['parameters']['service-dir']['default'] + package_dir: str = yaml_json['options']['@azure-tools/typespec-java']['package-dir'] + if 'namespace' not in yaml_json['options']['@azure-tools/typespec-java']: + log_and_print_error( + '[VALIDATE][tspconfig.yaml] ' + 'options.@azure-tools/typespec-java.namespace is REQUIRED for Java SDK. ' + 'E.g. "com.azure.ai.openai".') + return False + namespace: str = yaml_json['options']['@azure-tools/typespec-java']['namespace'] + + # validate service-dir + service_dir_segments = service_dir.split('/') + if not re.fullmatch(service_dir_pattern, service_dir): + valid = False + log_and_print_error( + '[VALIDATE][tspconfig.yaml] ' + 'parameters.service-dir.default SHOULD be "sdk/". ' + 'See https://azure.github.io/azure-sdk/policies_repostructure.html. ' + f'Current value: {service_dir}') + + # validate package_dir + if not re.fullmatch(package_dir_pattern, package_dir): + valid = False + log_and_print_error( + '[VALIDATE][tspconfig.yaml] ' + 'options.@azure-tools/typespec-java.package-dir SHOULD start with "azure-". ' + 'E.g. "azure-ai-openai". ' + f'Current value: {package_dir}') + + # validate namespace + if not re.fullmatch(namespace_pattern, namespace): + valid = False + log_and_print_error( + '[VALIDATE][tspconfig.yaml] ' + 'options.@azure-tools/typespec-java.namespace SHOULD start with "com.azure.". ' + 'E.g. "com.azure.ai.openai". ' + f'Current value: {namespace}') + + # validate package_dir matches namespace + if valid: + expected_package_dir = namespace[4:].replace('.', '-') + if expected_package_dir != package_dir: + valid = False + log_and_print_error( + '[VALIDATE][tspconfig.yaml] package_dir does not match namespace. ' + f'Expected package_dir from namespace "{namespace}" is: {expected_package_dir}') + + return valid + + +def log_and_print_error(error_message: str): + logging.error(error_message) + print(error_message, file=sys.stderr) diff --git a/eng/pipelines/docindex.yml b/eng/pipelines/docindex.yml index 0cb3f62059086..c128f858955d8 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/jobs/ci.tests.yml b/eng/pipelines/templates/jobs/ci.tests.yml index 0ab1e7181137b..76216700d81a0 100644 --- a/eng/pipelines/templates/jobs/ci.tests.yml +++ b/eng/pipelines/templates/jobs/ci.tests.yml @@ -47,7 +47,7 @@ parameters: default: 60 jobs: - - job: Test_${{ parameters.OSName }} + - job: displayName: 'Test' dependsOn: - ${{ parameters.DependsOn }} diff --git a/eng/pipelines/templates/jobs/live.tests.yml b/eng/pipelines/templates/jobs/live.tests.yml index 89d1058057a55..f909cf7599fc8 100644 --- a/eng/pipelines/templates/jobs/live.tests.yml +++ b/eng/pipelines/templates/jobs/live.tests.yml @@ -24,7 +24,7 @@ parameters: OSName: jobs: - - job: LiveTest_${{ parameters.OSName }} + - job: dependsOn: ${{ parameters.DependsOn }} condition: and(succeededOrFailed(), ne(${{ parameters.Matrix }}, '{}')) strategy: diff --git a/eng/pipelines/templates/jobs/native.live.tests.yml b/eng/pipelines/templates/jobs/native.live.tests.yml index 4fde913f5fa78..7c11d07251cb2 100644 --- a/eng/pipelines/templates/jobs/native.live.tests.yml +++ b/eng/pipelines/templates/jobs/native.live.tests.yml @@ -66,7 +66,7 @@ parameters: type: string jobs: - - job: NativeLiveTest_${{ parameters.OSName }} + - job: dependsOn: ${{ parameters.DependsOn }} condition: and(succeededOrFailed(), ne(${{ parameters.Matrix }}, '{}')) strategy: diff --git a/eng/pipelines/templates/stages/archetype-java-release-batch.yml b/eng/pipelines/templates/stages/archetype-java-release-batch.yml index 24a2d7c7e7235..7b0cf09454278 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 50e817b937fda..c22cff36f32ca 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 bcb7e5c37892d..6d689be35605c 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 0000000000000..904e04402123b --- /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/repo-docs/docms/daily.update.setting.xml b/eng/repo-docs/docms/daily.update.setting.xml index fc1b359a3a629..f30128b6d1461 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 27cfa73218be7..dfbd0f1ba16c4 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 0000000000000..a6a3a43c3a047 --- /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 156b35c15430d..d5644c7332699 100644 --- a/eng/versioning/external_dependencies.txt +++ b/eng/versioning/external_dependencies.txt @@ -255,7 +255,7 @@ org.junit.platform:junit-platform-testkit;1.9.3 org.junit.vintage:junit-vintage-engine;5.9.3 org.openjdk.jmh:jmh-core;1.37 org.openjdk.jmh:jmh-generator-annprocess;1.37 -org.spockframework:spock-core;2.4-M1-groovy-4.0 +org.spockframework:spock-core;2.4-M4-groovy-4.0 org.testng:testng;7.5.1 org.awaitility:awaitility;4.2.0 uk.org.lidalia:slf4j-test;1.2.0 diff --git a/eng/versioning/version_client.txt b/eng/versioning/version_client.txt index 6039240058c65..929867694a4cb 100644 --- a/eng/versioning/version_client.txt +++ b/eng/versioning/version_client.txt @@ -76,44 +76,43 @@ com.azure:azure-communication-email;1.0.12;1.1.0-beta.1 com.azure:azure-communication-identity;1.5.4;1.6.0-beta.1 com.azure:azure-communication-jobrouter;1.1.3;2.0.0-beta.1 com.azure:azure-communication-messages;1.0.2;1.1.0-beta.1 -com.azure:azure-communication-networktraversal;1.1.0;1.2.0-beta.1 com.azure:azure-communication-phonenumbers;1.1.12;1.2.0-beta.4 com.azure:azure-communication-rooms;1.1.1;1.2.0-beta.1 com.azure:azure-communication-sms;1.1.23;1.2.0-beta.1 com.azure:azure-containers-containerregistry;1.2.7;1.3.0-beta.1 com.azure:azure-containers-containerregistry-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-core;1.48.0;1.49.0-beta.1 -com.azure:azure-core-amqp;2.9.3;2.10.0-beta.1 +com.azure:azure-core;1.49.0;1.50.0-beta.1 +com.azure:azure-core-amqp;2.9.4;2.10.0-beta.1 com.azure:azure-core-amqp-experimental;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-core-experimental;1.0.0-beta.49;1.0.0-beta.50 -com.azure:azure-core-http-jdk-httpclient;1.0.0-beta.12;1.0.0-beta.13 -com.azure:azure-core-http-netty;1.14.2;1.15.0-beta.1 -com.azure:azure-core-http-okhttp;1.11.20;1.12.0-beta.1 -com.azure:azure-core-http-vertx;1.0.0-beta.17;1.0.0-beta.18 -com.azure:azure-core-management;1.13.0;1.14.0-beta.1 -com.azure:azure-core-metrics-opentelemetry;1.0.0-beta.18;1.0.0-beta.19 +com.azure:azure-core-experimental;1.0.0-beta.50;1.0.0-beta.51 +com.azure:azure-core-http-jdk-httpclient;1.0.0-beta.13;1.0.0-beta.14 +com.azure:azure-core-http-netty;1.15.0;1.16.0-beta.1 +com.azure:azure-core-http-okhttp;1.11.21;1.12.0-beta.1 +com.azure:azure-core-http-vertx;1.0.0-beta.18;1.0.0-beta.19 +com.azure:azure-core-management;1.14.0;1.15.0-beta.1 +com.azure:azure-core-metrics-opentelemetry;1.0.0-beta.19;1.0.0-beta.20 com.azure:azure-core-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-core-serializer-avro-apache;1.0.0-beta.45;1.0.0-beta.46 +com.azure:azure-core-serializer-avro-apache;1.0.0-beta.46;1.0.0-beta.47 com.azure:azure-core-serializer-avro-jackson;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-core-serializer-json-gson;1.2.11;1.3.0-beta.1 -com.azure:azure-core-serializer-json-jackson;1.4.11;1.5.0-beta.1 -com.azure:azure-core-test;1.24.2;1.25.0-beta.1 -com.azure:azure-core-tracing-opentelemetry;1.0.0-beta.45;1.0.0-beta.46 +com.azure:azure-core-serializer-json-gson;1.2.12;1.3.0-beta.1 +com.azure:azure-core-serializer-json-jackson;1.4.12;1.5.0-beta.1 +com.azure:azure-core-test;1.25.0;1.26.0-beta.1 +com.azure:azure-core-tracing-opentelemetry;1.0.0-beta.46;1.0.0-beta.47 com.azure:azure-core-tracing-opentelemetry-samples;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-core-version-tests;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-cosmos;4.58.0;4.59.0 +com.azure:azure-cosmos;4.59.0;4.60.0-beta.1 com.azure:azure-cosmos-benchmark;4.0.1-beta.1;4.0.1-beta.1 com.azure:azure-cosmos-dotnet-benchmark;4.0.1-beta.1;4.0.1-beta.1 com.azure.cosmos.spark:azure-cosmos-spark_3_2-12;1.0.0-beta.1;1.0.0-beta.1 +com.azure:azure-cosmos-encryption;2.11.0;2.12.0-beta.1 com.azure.cosmos.spark:azure-cosmos-spark_3-1_2-12;4.30.0;4.31.0-beta.1 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-encryption;2.10.0;2.11.0 com.azure:azure-cosmos-test;1.0.0-beta.6;1.0.0-beta.7 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.1;1.0.0-beta.2 +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 com.azure:azure-data-appconfiguration-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-data-schemaregistry;1.4.5;1.5.0-beta.1 @@ -121,16 +120,16 @@ com.azure:azure-data-schemaregistry-apacheavro;1.1.16;1.2.0-beta.2 com.azure:azure-data-schemaregistry-jsonschema;1.0.0-beta.1;1.0.0-beta.2 com.azure:azure-data-tables;12.4.0;12.5.0-beta.1 com.azure:azure-data-tables-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-developer-devcenter;1.0.0-beta.3;1.0.0 +com.azure:azure-developer-devcenter;1.0.0;1.1.0-beta.1 com.azure:azure-developer-loadtesting;1.0.12;1.1.0-beta.1 com.azure:azure-digitaltwins-core;1.3.19;1.4.0-beta.1 com.azure:azure-e2e;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-health-insights-clinicalmatching;1.0.0-beta.1;1.0.0-beta.2 com.azure:azure-health-insights-cancerprofiling;1.0.0-beta.1;1.0.0-beta.2 com.azure:azure-health-insights-radiologyinsights;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-identity;1.12.0;1.13.0-beta.1 +com.azure:azure-identity;1.12.1;1.13.0-beta.1 com.azure:azure-identity-extensions;1.1.15;1.2.0-beta.2 -com.azure:azure-identity-broker;1.1.0;1.2.0-beta.1 +com.azure:azure-identity-broker;1.1.1;1.2.0-beta.1 com.azure:azure-identity-broker-samples;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-identity-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-iot-deviceupdate;1.0.17;1.1.0-beta.1 @@ -175,11 +174,11 @@ com.azure:azure-search-documents;11.6.4;11.7.0-beta.3 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 -com.azure:azure-security-keyvault-administration;4.5.2;4.6.0-beta.1 +com.azure:azure-security-keyvault-administration;4.5.3;4.6.0-beta.1 com.azure:azure-security-keyvault-certificates;4.6.2;4.7.0-beta.1 com.azure:azure-security-keyvault-jca;2.8.1;2.9.0-beta.1 com.azure:azure-security-test-keyvault-jca;1.0.0;1.0.0 -com.azure:azure-security-keyvault-keys;4.8.2;4.9.0-beta.1 +com.azure:azure-security-keyvault-keys;4.8.3;4.9.0-beta.1 com.azure:azure-security-keyvault-secrets;4.8.2;4.9.0-beta.1 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 @@ -471,8 +470,6 @@ com.azure.tools:azure-sdk-build-tool;1.0.0;1.1.0-beta.1 # In the pom, the version update tag after the version should name the unreleased package and the dependency version: # -unreleased_com.azure:azure-core-amqp;2.10.0-beta.1 - # Released Beta dependencies: Copy the entry from above, prepend "beta_", remove the current # version and set the version to the released beta. Released beta dependencies are only valid # for dependency versions. These entries are specifically for when we've released a beta for diff --git a/sdk/advisor/azure-resourcemanager-advisor/pom.xml b/sdk/advisor/azure-resourcemanager-advisor/pom.xml index d785f2cadcf23..3f49cd7912ac3 100644 --- a/sdk/advisor/azure-resourcemanager-advisor/pom.xml +++ b/sdk/advisor/azure-resourcemanager-advisor/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/agrifood/azure-resourcemanager-agrifood/pom.xml b/sdk/agrifood/azure-resourcemanager-agrifood/pom.xml index 4da2313f71327..58ad6195afda6 100644 --- a/sdk/agrifood/azure-resourcemanager-agrifood/pom.xml +++ b/sdk/agrifood/azure-resourcemanager-agrifood/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/agrifood/azure-verticals-agrifood-farming/README.md b/sdk/agrifood/azure-verticals-agrifood-farming/README.md index f4bb0853dab33..d8d1efe2230ca 100644 --- a/sdk/agrifood/azure-verticals-agrifood-farming/README.md +++ b/sdk/agrifood/azure-verticals-agrifood-farming/README.md @@ -47,7 +47,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.11.4 + 1.12.0 ``` diff --git a/sdk/agrifood/azure-verticals-agrifood-farming/pom.xml b/sdk/agrifood/azure-verticals-agrifood-farming/pom.xml index 1c15857fb2c44..2380e6c807a5c 100644 --- a/sdk/agrifood/azure-verticals-agrifood-farming/pom.xml +++ b/sdk/agrifood/azure-verticals-agrifood-farming/pom.xml @@ -43,17 +43,17 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-experimental - 1.0.0-beta.49 + 1.0.0-beta.50 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -78,13 +78,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -102,7 +102,7 @@ com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 test diff --git a/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/pom.xml b/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/pom.xml index 7cf16d9c4bf85..03eba29e73896 100644 --- a/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/pom.xml +++ b/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/README.md b/sdk/anomalydetector/azure-ai-anomalydetector/README.md index a3cfe120f28d2..ce8a013634369 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/README.md +++ b/sdk/anomalydetector/azure-ai-anomalydetector/README.md @@ -54,7 +54,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.11.4 + 1.12.0 ``` diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/pom.xml b/sdk/anomalydetector/azure-ai-anomalydetector/pom.xml index d29c9b4e9f8d9..f502c66f4eac6 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/pom.xml +++ b/sdk/anomalydetector/azure-ai-anomalydetector/pom.xml @@ -45,12 +45,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -75,13 +75,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/aot/azure-aot-graalvm-samples/pom.xml b/sdk/aot/azure-aot-graalvm-samples/pom.xml index d624785163375..a2fb966605e43 100644 --- a/sdk/aot/azure-aot-graalvm-samples/pom.xml +++ b/sdk/aot/azure-aot-graalvm-samples/pom.xml @@ -66,12 +66,12 @@ com.azure azure-identity - 1.12.0 + 1.12.1 com.azure azure-security-keyvault-keys - 4.8.2 + 4.8.3 com.azure @@ -98,7 +98,7 @@ com.azure azure-cosmos - 4.58.0 + 4.59.0 com.azure diff --git a/sdk/apicenter/azure-resourcemanager-apicenter/pom.xml b/sdk/apicenter/azure-resourcemanager-apicenter/pom.xml index 8e76961c4592f..26b29c6f3e3e9 100644 --- a/sdk/apicenter/azure-resourcemanager-apicenter/pom.xml +++ b/sdk/apicenter/azure-resourcemanager-apicenter/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/apimanagement/azure-resourcemanager-apimanagement/pom.xml b/sdk/apimanagement/azure-resourcemanager-apimanagement/pom.xml index 532fc2afb94bf..ef492c6d15c3b 100644 --- a/sdk/apimanagement/azure-resourcemanager-apimanagement/pom.xml +++ b/sdk/apimanagement/azure-resourcemanager-apimanagement/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/pom.xml b/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/pom.xml index f3034c9f650fe..5c162a6ee8f64 100644 --- a/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/pom.xml +++ b/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/appconfiguration/azure-data-appconfiguration-perf/pom.xml b/sdk/appconfiguration/azure-data-appconfiguration-perf/pom.xml index e88095e820324..ffee58abad694 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration-perf/pom.xml +++ b/sdk/appconfiguration/azure-data-appconfiguration-perf/pom.xml @@ -38,12 +38,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -97,7 +97,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 diff --git a/sdk/appconfiguration/azure-data-appconfiguration/pom.xml b/sdk/appconfiguration/azure-data-appconfiguration/pom.xml index f0444709d65a0..99f0286fb4a0f 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/pom.xml +++ b/sdk/appconfiguration/azure-data-appconfiguration/pom.xml @@ -51,7 +51,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -61,25 +61,25 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -115,7 +115,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -130,7 +130,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 3d0c3e5a491e5..744dddcf1bee5 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/appconfiguration/azure-resourcemanager-appconfiguration/pom.xml b/sdk/appconfiguration/azure-resourcemanager-appconfiguration/pom.xml index 2149739bd7a18..5d3a96e9709bd 100644 --- a/sdk/appconfiguration/azure-resourcemanager-appconfiguration/pom.xml +++ b/sdk/appconfiguration/azure-resourcemanager-appconfiguration/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/appcontainers/azure-resourcemanager-appcontainers/pom.xml b/sdk/appcontainers/azure-resourcemanager-appcontainers/pom.xml index f1f9bd039df02..06f2996e3bf5d 100644 --- a/sdk/appcontainers/azure-resourcemanager-appcontainers/pom.xml +++ b/sdk/appcontainers/azure-resourcemanager-appcontainers/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/pom.xml b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/pom.xml index b75803d31f0df..3e979aa60ffc0 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/pom.xml +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/astro/azure-resourcemanager-astro/pom.xml b/sdk/astro/azure-resourcemanager-astro/pom.xml index 023395aef5133..530459379db5d 100644 --- a/sdk/astro/azure-resourcemanager-astro/pom.xml +++ b/sdk/astro/azure-resourcemanager-astro/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/attestation/azure-resourcemanager-attestation/pom.xml b/sdk/attestation/azure-resourcemanager-attestation/pom.xml index a8058c54526cd..6e80cee07a281 100644 --- a/sdk/attestation/azure-resourcemanager-attestation/pom.xml +++ b/sdk/attestation/azure-resourcemanager-attestation/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/attestation/azure-security-attestation/pom.xml b/sdk/attestation/azure-security-attestation/pom.xml index d22798b09205e..df72c66926162 100644 --- a/sdk/attestation/azure-security-attestation/pom.xml +++ b/sdk/attestation/azure-security-attestation/pom.xml @@ -45,7 +45,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.nimbusds @@ -65,13 +65,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 test @@ -113,19 +113,19 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -176,7 +176,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/attestation/azure-security-attestation/src/test/java/com/azure/security/attestation/AttestationClientTestBase.java b/sdk/attestation/azure-security-attestation/src/test/java/com/azure/security/attestation/AttestationClientTestBase.java index d4a73ffa359eb..f109fd517c3d9 100644 --- a/sdk/attestation/azure-security-attestation/src/test/java/com/azure/security/attestation/AttestationClientTestBase.java +++ b/sdk/attestation/azure-security-attestation/src/test/java/com/azure/security/attestation/AttestationClientTestBase.java @@ -27,10 +27,7 @@ import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.x509.X509V3CertificateGenerator; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.parallel.Isolated; import org.junit.jupiter.params.provider.Arguments; @@ -85,6 +82,9 @@ public class AttestationClientTestBase extends TestProxyTestBase { protected void beforeTest() { super.beforeTest(); + GlobalOpenTelemetry.resetForTest(); + tracer = configureLoggingExporter(testContextManager.getTestName()); + if (interceptorManager.isPlaybackMode()) { interceptorManager.addMatchers(Collections.singletonList(new CustomMatcher() .setHeadersKeyOnlyMatch(Collections.singletonList("Authorization")))); @@ -122,21 +122,8 @@ public static void beforeAll() { } @Override - @BeforeEach - public void setupTest(TestInfo testInfo) { - GlobalOpenTelemetry.resetForTest(); - super.setupTest(testInfo); - String testMethod = testInfo.getTestMethod().isPresent() - ? testInfo.getTestMethod().get().getName() - : testInfo.getDisplayName(); - tracer = configureLoggingExporter(testMethod); - } - - @Override - @AfterEach - public void teardownTest(TestInfo testInfo) { + public void afterTest() { GlobalOpenTelemetry.resetForTest(); - super.teardownTest(testInfo); } @SuppressWarnings({"deprecation", "resource"}) 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 21c89af0fc578..0dada17dbdf1f 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/automanage/azure-resourcemanager-automanage/pom.xml b/sdk/automanage/azure-resourcemanager-automanage/pom.xml index 86b26375f5d14..c657f12b9fc43 100644 --- a/sdk/automanage/azure-resourcemanager-automanage/pom.xml +++ b/sdk/automanage/azure-resourcemanager-automanage/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/automation/azure-resourcemanager-automation/pom.xml b/sdk/automation/azure-resourcemanager-automation/pom.xml index 8cb4888b2e0c5..a02970947ab88 100644 --- a/sdk/automation/azure-resourcemanager-automation/pom.xml +++ b/sdk/automation/azure-resourcemanager-automation/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/avs/azure-resourcemanager-avs/pom.xml b/sdk/avs/azure-resourcemanager-avs/pom.xml index cebadcc901736..e5e8bfc777125 100644 --- a/sdk/avs/azure-resourcemanager-avs/pom.xml +++ b/sdk/avs/azure-resourcemanager-avs/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/azureadexternalidentities/azure-resourcemanager-azureadexternalidentities/pom.xml b/sdk/azureadexternalidentities/azure-resourcemanager-azureadexternalidentities/pom.xml index 6a65d7fa0bbbb..a9558cb5a4d3e 100644 --- a/sdk/azureadexternalidentities/azure-resourcemanager-azureadexternalidentities/pom.xml +++ b/sdk/azureadexternalidentities/azure-resourcemanager-azureadexternalidentities/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/azurearcdata/azure-resourcemanager-azurearcdata/pom.xml b/sdk/azurearcdata/azure-resourcemanager-azurearcdata/pom.xml index 58ebaaa4ae709..54953c5f3885e 100644 --- a/sdk/azurearcdata/azure-resourcemanager-azurearcdata/pom.xml +++ b/sdk/azurearcdata/azure-resourcemanager-azurearcdata/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/azurestack/azure-resourcemanager-azurestack/pom.xml b/sdk/azurestack/azure-resourcemanager-azurestack/pom.xml index 45b4663f8ab5f..95aaa1cf35ecc 100644 --- a/sdk/azurestack/azure-resourcemanager-azurestack/pom.xml +++ b/sdk/azurestack/azure-resourcemanager-azurestack/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/azurestackhci/azure-resourcemanager-azurestackhci/pom.xml b/sdk/azurestackhci/azure-resourcemanager-azurestackhci/pom.xml index 0e44cc40a922f..5d1c3579d9388 100644 --- a/sdk/azurestackhci/azure-resourcemanager-azurestackhci/pom.xml +++ b/sdk/azurestackhci/azure-resourcemanager-azurestackhci/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/pom.xml b/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/pom.xml index f86a52c52dada..a2a91feb2726d 100644 --- a/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/pom.xml +++ b/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/batch/azure-resourcemanager-batch/pom.xml b/sdk/batch/azure-resourcemanager-batch/pom.xml index 487a7e92a780a..a9b8d0b6aae57 100644 --- a/sdk/batch/azure-resourcemanager-batch/pom.xml +++ b/sdk/batch/azure-resourcemanager-batch/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/batch/microsoft-azure-batch/pom.xml b/sdk/batch/microsoft-azure-batch/pom.xml index baaac2e5e4b39..31052dbcd5657 100644 --- a/sdk/batch/microsoft-azure-batch/pom.xml +++ b/sdk/batch/microsoft-azure-batch/pom.xml @@ -85,7 +85,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 test diff --git a/sdk/batchai/azure-resourcemanager-batchai/pom.xml b/sdk/batchai/azure-resourcemanager-batchai/pom.xml index c538571a51334..2035872f4e34f 100644 --- a/sdk/batchai/azure-resourcemanager-batchai/pom.xml +++ b/sdk/batchai/azure-resourcemanager-batchai/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/billing/azure-resourcemanager-billing/pom.xml b/sdk/billing/azure-resourcemanager-billing/pom.xml index 007972bef8cbc..67408a92ec323 100644 --- a/sdk/billing/azure-resourcemanager-billing/pom.xml +++ b/sdk/billing/azure-resourcemanager-billing/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/billingbenefits/azure-resourcemanager-billingbenefits/pom.xml b/sdk/billingbenefits/azure-resourcemanager-billingbenefits/pom.xml index 7706a866723a5..771f4180eec17 100644 --- a/sdk/billingbenefits/azure-resourcemanager-billingbenefits/pom.xml +++ b/sdk/billingbenefits/azure-resourcemanager-billingbenefits/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/botservice/azure-resourcemanager-botservice/pom.xml b/sdk/botservice/azure-resourcemanager-botservice/pom.xml index 5f8ff020a7494..40a6cbf19b52c 100644 --- a/sdk/botservice/azure-resourcemanager-botservice/pom.xml +++ b/sdk/botservice/azure-resourcemanager-botservice/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/changeanalysis/azure-resourcemanager-changeanalysis/pom.xml b/sdk/changeanalysis/azure-resourcemanager-changeanalysis/pom.xml index 80c5e532eaa5f..3f6b292e38c46 100644 --- a/sdk/changeanalysis/azure-resourcemanager-changeanalysis/pom.xml +++ b/sdk/changeanalysis/azure-resourcemanager-changeanalysis/pom.xml @@ -45,12 +45,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure.resourcemanager @@ -61,13 +61,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/chaos/azure-resourcemanager-chaos/pom.xml b/sdk/chaos/azure-resourcemanager-chaos/pom.xml index b12880124c84c..a924e5895b85e 100644 --- a/sdk/chaos/azure-resourcemanager-chaos/pom.xml +++ b/sdk/chaos/azure-resourcemanager-chaos/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/pom.xml b/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/pom.xml index 76ac0f6e23a41..40b46a3faee93 100644 --- a/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/pom.xml +++ b/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/commerce/azure-resourcemanager-commerce/pom.xml b/sdk/commerce/azure-resourcemanager-commerce/pom.xml index f968aa560610c..3ada1b25ccb8f 100644 --- a/sdk/commerce/azure-resourcemanager-commerce/pom.xml +++ b/sdk/commerce/azure-resourcemanager-commerce/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/communication/azure-communication-callautomation/assets.json b/sdk/communication/azure-communication-callautomation/assets.json index ec0e7a17712ff..7516f0a2577fa 100644 --- a/sdk/communication/azure-communication-callautomation/assets.json +++ b/sdk/communication/azure-communication-callautomation/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/communication/azure-communication-callautomation", - "Tag": "java/communication/azure-communication-callautomation_bde5640047" + "Tag": "java/communication/azure-communication-callautomation_ea89bbe13c" } \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/pom.xml b/sdk/communication/azure-communication-callautomation/pom.xml index d12d3c6618192..32b5e27eb7b87 100644 --- a/sdk/communication/azure-communication-callautomation/pom.xml +++ b/sdk/communication/azure-communication-callautomation/pom.xml @@ -55,7 +55,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -77,7 +77,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -119,19 +119,19 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -147,6 +147,11 @@ test 0.8.12 + + com.azure + azure-core-http-netty + 1.15.0 + @@ -196,7 +201,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallAutomationAsyncClient.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallAutomationAsyncClient.java index c757a03ffc1eb..ac96bc8dcd77a 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallAutomationAsyncClient.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallAutomationAsyncClient.java @@ -351,8 +351,7 @@ Mono> answerCallWithResponseInternal(AnswerCallOption .setIncomingCallContext(answerCallOptions.getIncomingCallContext()) .setCallbackUri(answerCallOptions.getCallbackUrl()) .setAnsweredBy(sourceIdentity) - .setOperationContext(answerCallOptions.getOperationContext()) - .setSourceCallerIdNumber(PhoneNumberIdentifierConverter.convert(answerCallOptions.getSourceCallerIdNumber())); + .setOperationContext(answerCallOptions.getOperationContext()); if (answerCallOptions.getCallIntelligenceOptions() != null && answerCallOptions.getCallIntelligenceOptions().getCognitiveServicesEndpoint() != null) { CallIntelligenceOptionsInternal callIntelligenceOptionsInternal = new CallIntelligenceOptionsInternal(); diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallAutomationEventParser.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallAutomationEventParser.java index a9a96b00a4c07..f130e5a14f6d0 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallAutomationEventParser.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallAutomationEventParser.java @@ -45,6 +45,9 @@ import com.azure.communication.callautomation.models.events.SendDtmfTonesCompleted; import com.azure.communication.callautomation.models.events.SendDtmfTonesFailed; import com.azure.communication.callautomation.models.events.TranscriptionUpdated; +import com.azure.communication.callautomation.models.events.MediaStreamingStarted; +import com.azure.communication.callautomation.models.events.MediaStreamingStopped; +import com.azure.communication.callautomation.models.events.MediaStreamingFailed; import com.azure.core.models.CloudEvent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.core.JsonProcessingException; @@ -190,6 +193,12 @@ private static CallAutomationEventBase parseSingleCloudEvent(String data, String ret = mapper.convertValue(eventData, CreateCallFailed.class); } else if (Objects.equals(eventType, "Microsoft.Communication.HoldFailed")) { ret = mapper.convertValue(eventData, HoldFailed.class); + } else if (Objects.equals(eventType, "Microsoft.Communication.MediaStreamingStarted")) { + ret = mapper.convertValue(eventData, MediaStreamingStarted.class); + } else if (Objects.equals(eventType, "Microsoft.Communication.MediaStreamingStopped")) { + ret = mapper.convertValue(eventData, MediaStreamingStopped.class); + } else if (Objects.equals(eventType, "Microsoft.Communication.MediaStreamingFailed")) { + ret = mapper.convertValue(eventData, MediaStreamingFailed.class); } return ret; } catch (RuntimeException e) { diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallConnectionAsync.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallConnectionAsync.java index 44ad8c818db7b..ee444b77727be 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallConnectionAsync.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallConnectionAsync.java @@ -40,6 +40,7 @@ import com.azure.communication.callautomation.models.UnmuteParticipantResult; import com.azure.communication.common.CommunicationIdentifier; import com.azure.communication.common.CommunicationUserIdentifier; +import com.azure.communication.common.MicrosoftTeamsAppIdentifier; import com.azure.communication.common.MicrosoftTeamsUserIdentifier; import com.azure.communication.common.PhoneNumberIdentifier; import com.azure.core.annotation.ReturnType; @@ -254,6 +255,8 @@ public Mono transferCallToParticipant(CommunicationIdentifie return transferCallToParticipantWithResponse(new TransferCallToParticipantOptions((PhoneNumberIdentifier) targetParticipant)).flatMap(FluxUtil::toMono); } else if (targetParticipant instanceof MicrosoftTeamsUserIdentifier) { return transferCallToParticipantWithResponse(new TransferCallToParticipantOptions((MicrosoftTeamsUserIdentifier) targetParticipant)).flatMap(FluxUtil::toMono); + } else if (targetParticipant instanceof MicrosoftTeamsAppIdentifier) { + return transferCallToParticipantWithResponse(new TransferCallToParticipantOptions((MicrosoftTeamsAppIdentifier) targetParticipant)).flatMap(FluxUtil::toMono); } else { throw logger.logExceptionAsError(new IllegalArgumentException("targetParticipant type is invalid.")); } @@ -281,7 +284,8 @@ Mono> transferCallToParticipantWithResponseInternal TransferToParticipantRequestInternal request = new TransferToParticipantRequestInternal() .setTargetParticipant(CommunicationIdentifierConverter.convert(transferCallToParticipantOptions.getTargetParticipant())) .setOperationContext(transferCallToParticipantOptions.getOperationContext()) - .setOperationCallbackUri(transferCallToParticipantOptions.getOperationCallbackUrl()); + .setOperationCallbackUri(transferCallToParticipantOptions.getOperationCallbackUrl()) + .setSourceCallerIdNumber(PhoneNumberIdentifierConverter.convert(transferCallToParticipantOptions.getSourceCallerIdNumber())); if (transferCallToParticipantOptions.getCustomCallingContext().getSipHeaders() != null || transferCallToParticipantOptions.getCustomCallingContext().getVoipHeaders() != null) { request.setCustomCallingContext(new CustomCallingContext() diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/converters/CommunicationIdentifierConverter.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/converters/CommunicationIdentifierConverter.java index e4bdae8e2bb2a..c1114b7fa85b7 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/converters/CommunicationIdentifierConverter.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/converters/CommunicationIdentifierConverter.java @@ -7,11 +7,13 @@ import com.azure.communication.callautomation.implementation.models.CommunicationIdentifierModel; import com.azure.communication.callautomation.implementation.models.CommunicationIdentifierModelKind; import com.azure.communication.callautomation.implementation.models.CommunicationUserIdentifierModel; +import com.azure.communication.callautomation.implementation.models.MicrosoftTeamsAppIdentifierModel; import com.azure.communication.callautomation.implementation.models.MicrosoftTeamsUserIdentifierModel; import com.azure.communication.callautomation.implementation.models.PhoneNumberIdentifierModel; import com.azure.communication.common.CommunicationCloudEnvironment; import com.azure.communication.common.CommunicationIdentifier; import com.azure.communication.common.CommunicationUserIdentifier; +import com.azure.communication.common.MicrosoftTeamsAppIdentifier; import com.azure.communication.common.MicrosoftTeamsUserIdentifier; import com.azure.communication.common.PhoneNumberIdentifier; import com.azure.communication.common.UnknownIdentifier; @@ -64,6 +66,16 @@ public static CommunicationIdentifier convert(CommunicationIdentifierModel ident .fromString(teamsUserIdentifierModel.getCloud().toString())); } + if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_APP + && identifier.getMicrosoftTeamsApp() != null) { + MicrosoftTeamsAppIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsApp(); + Objects.requireNonNull(teamsUserIdentifierModel.getAppId(), "'AppId' of the CommunicationIdentifierModel cannot be null."); + Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); + Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); + return new MicrosoftTeamsAppIdentifier(teamsUserIdentifierModel.getAppId(), + CommunicationCloudEnvironment.fromString(teamsUserIdentifierModel.getCloud().toString())); + } + Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); } @@ -104,6 +116,16 @@ public static CommunicationIdentifierModel convert(CommunicationIdentifier ident teamsUserIdentifier.getCloudEnvironment().toString()))); } + if (identifier instanceof MicrosoftTeamsAppIdentifier) { + MicrosoftTeamsAppIdentifier teamsAppIdentifier = (MicrosoftTeamsAppIdentifier) identifier; + return new CommunicationIdentifierModel() + .setRawId(teamsAppIdentifier.getRawId()) + .setMicrosoftTeamsApp(new MicrosoftTeamsAppIdentifierModel() + .setAppId(teamsAppIdentifier.getAppId()) + .setCloud(CommunicationCloudEnvironmentModel.fromString( + teamsAppIdentifier.getCloudEnvironment().toString()))); + } + if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); @@ -116,6 +138,7 @@ private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); + MicrosoftTeamsAppIdentifierModel microsoftTeamsApp = identifier.getMicrosoftTeamsApp(); ArrayList presentProperties = new ArrayList<>(); if (communicationUser != null) { @@ -127,6 +150,9 @@ private static void assertSingleType(CommunicationIdentifierModel identifier) { if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } + if (microsoftTeamsApp != null) { + presentProperties.add(microsoftTeamsApp.getClass().getName()); + } if (presentProperties.size() > 1) { throw new IllegalArgumentException( @@ -147,6 +173,9 @@ private static CommunicationIdentifierModelKind extractKind(CommunicationIdentif if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } + if (identifier.getMicrosoftTeamsApp() != null) { + return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_APP; + } return CommunicationIdentifierModelKind.UNKNOWN; } } diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/AnswerCallRequestInternal.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/AnswerCallRequestInternal.java index d0c3c28ceb908..21bba97a26c46 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/AnswerCallRequestInternal.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/AnswerCallRequestInternal.java @@ -52,15 +52,6 @@ public final class AnswerCallRequestInternal { @JsonProperty(value = "answeredBy") private CommunicationUserIdentifierModel answeredBy; - /* - * The source caller Id, a phone number, that's will be used when inviting - * a pstn target. - * Required only when transferring call to PSTN, if this is an incoming - * voip call. - */ - @JsonProperty(value = "sourceCallerIdNumber") - private PhoneNumberIdentifierModel sourceCallerIdNumber; - /** * Get the incomingCallContext property: The context associated with the call. * @@ -203,26 +194,4 @@ public AnswerCallRequestInternal setAnsweredBy(CommunicationUserIdentifierModel this.answeredBy = answeredBy; return this; } - - /** - * Get the sourceCallerIdNumber property: The source caller Id, a phone number, that's will be used when inviting a - * pstn target. Required only when transferring call to PSTN, if this is an incoming voip call. - * - * @return the sourceCallerIdNumber value. - */ - public PhoneNumberIdentifierModel getSourceCallerIdNumber() { - return this.sourceCallerIdNumber; - } - - /** - * Set the sourceCallerIdNumber property: The source caller Id, a phone number, that's will be used when inviting a - * pstn target. Required only when transferring call to PSTN, if this is an incoming voip call. - * - * @param sourceCallerIdNumber the sourceCallerIdNumber value to set. - * @return the AnswerCallRequestInternal object itself. - */ - public AnswerCallRequestInternal setSourceCallerIdNumber(PhoneNumberIdentifierModel sourceCallerIdNumber) { - this.sourceCallerIdNumber = sourceCallerIdNumber; - return this; - } } diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingFailed.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingFailed.java new file mode 100644 index 0000000000000..4f7e6eb921a6a --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingFailed.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.communication.callautomation.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** The MediaStreamingFailed model. */ +@Immutable +public final class MediaStreamingFailed { + /* + * Used by customers when calling mid-call actions to correlate the request + * to the response event. + */ + @JsonProperty(value = "operationContext", access = JsonProperty.Access.WRITE_ONLY) + private String operationContext; + + /* + * Contains the resulting SIP code, sub-code and message. + */ + @JsonProperty(value = "resultInformation", access = JsonProperty.Access.WRITE_ONLY) + private ResultInformation resultInformation; + + /* + * Defines the result for audio streaming update with the current status + * and the details about the status + */ + @JsonProperty(value = "mediaStreamingUpdate", access = JsonProperty.Access.WRITE_ONLY) + private MediaStreamingUpdate mediaStreamingUpdate; + + /* + * Call connection ID. + */ + @JsonProperty(value = "callConnectionId", access = JsonProperty.Access.WRITE_ONLY) + private String callConnectionId; + + /* + * Server call ID. + */ + @JsonProperty(value = "serverCallId", access = JsonProperty.Access.WRITE_ONLY) + private String serverCallId; + + /* + * Correlation ID for event to call correlation. Also called ChainId for + * skype chain ID. + */ + @JsonProperty(value = "correlationId", access = JsonProperty.Access.WRITE_ONLY) + private String correlationId; + + /** + * Get the operationContext property: Used by customers when calling mid-call actions to correlate the request to + * the response event. + * + * @return the operationContext value. + */ + public String getOperationContext() { + return this.operationContext; + } + + /** + * Get the resultInformation property: Contains the resulting SIP code, sub-code and message. + * + * @return the resultInformation value. + */ + public ResultInformation getResultInformation() { + return this.resultInformation; + } + + /** + * Get the mediaStreamingUpdate property: Defines the result for audio streaming update with the current status and + * the details about the status. + * + * @return the mediaStreamingUpdate value. + */ + public MediaStreamingUpdate getMediaStreamingUpdate() { + return this.mediaStreamingUpdate; + } + + /** + * Get the callConnectionId property: Call connection ID. + * + * @return the callConnectionId value. + */ + public String getCallConnectionId() { + return this.callConnectionId; + } + + /** + * Get the serverCallId property: Server call ID. + * + * @return the serverCallId value. + */ + public String getServerCallId() { + return this.serverCallId; + } + + /** + * Get the correlationId property: Correlation ID for event to call correlation. Also called ChainId for skype chain + * ID. + * + * @return the correlationId value. + */ + public String getCorrelationId() { + return this.correlationId; + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStarted.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStarted.java new file mode 100644 index 0000000000000..de6ff9beb0578 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStarted.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.communication.callautomation.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** The MediaStreamingStarted model. */ +@Immutable +public final class MediaStreamingStarted { + /* + * Used by customers when calling mid-call actions to correlate the request + * to the response event. + */ + @JsonProperty(value = "operationContext", access = JsonProperty.Access.WRITE_ONLY) + private String operationContext; + + /* + * Contains the resulting SIP code, sub-code and message. + */ + @JsonProperty(value = "resultInformation", access = JsonProperty.Access.WRITE_ONLY) + private ResultInformation resultInformation; + + /* + * Defines the result for audio streaming update with the current status + * and the details about the status + */ + @JsonProperty(value = "mediaStreamingUpdate", access = JsonProperty.Access.WRITE_ONLY) + private MediaStreamingUpdate mediaStreamingUpdate; + + /* + * Call connection ID. + */ + @JsonProperty(value = "callConnectionId", access = JsonProperty.Access.WRITE_ONLY) + private String callConnectionId; + + /* + * Server call ID. + */ + @JsonProperty(value = "serverCallId", access = JsonProperty.Access.WRITE_ONLY) + private String serverCallId; + + /* + * Correlation ID for event to call correlation. Also called ChainId for + * skype chain ID. + */ + @JsonProperty(value = "correlationId", access = JsonProperty.Access.WRITE_ONLY) + private String correlationId; + + /** + * Get the operationContext property: Used by customers when calling mid-call actions to correlate the request to + * the response event. + * + * @return the operationContext value. + */ + public String getOperationContext() { + return this.operationContext; + } + + /** + * Get the resultInformation property: Contains the resulting SIP code, sub-code and message. + * + * @return the resultInformation value. + */ + public ResultInformation getResultInformation() { + return this.resultInformation; + } + + /** + * Get the mediaStreamingUpdate property: Defines the result for audio streaming update with the current status and + * the details about the status. + * + * @return the mediaStreamingUpdate value. + */ + public MediaStreamingUpdate getMediaStreamingUpdate() { + return this.mediaStreamingUpdate; + } + + /** + * Get the callConnectionId property: Call connection ID. + * + * @return the callConnectionId value. + */ + public String getCallConnectionId() { + return this.callConnectionId; + } + + /** + * Get the serverCallId property: Server call ID. + * + * @return the serverCallId value. + */ + public String getServerCallId() { + return this.serverCallId; + } + + /** + * Get the correlationId property: Correlation ID for event to call correlation. Also called ChainId for skype chain + * ID. + * + * @return the correlationId value. + */ + public String getCorrelationId() { + return this.correlationId; + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStatus.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStatus.java new file mode 100644 index 0000000000000..84ae9e81ff18d --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStatus.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.communication.callautomation.implementation.models; + +import com.azure.core.util.ExpandableStringEnum; +import com.fasterxml.jackson.annotation.JsonCreator; +import java.util.Collection; + +/** Defines values for MediaStreamingStatus. */ +public final class MediaStreamingStatus extends ExpandableStringEnum { + /** Static value mediaStreamingStarted for MediaStreamingStatus. */ + public static final MediaStreamingStatus MEDIA_STREAMING_STARTED = fromString("mediaStreamingStarted"); + + /** Static value mediaStreamingFailed for MediaStreamingStatus. */ + public static final MediaStreamingStatus MEDIA_STREAMING_FAILED = fromString("mediaStreamingFailed"); + + /** Static value mediaStreamingStopped for MediaStreamingStatus. */ + public static final MediaStreamingStatus MEDIA_STREAMING_STOPPED = fromString("mediaStreamingStopped"); + + /** Static value unspecifiedError for MediaStreamingStatus. */ + public static final MediaStreamingStatus UNSPECIFIED_ERROR = fromString("unspecifiedError"); + + /** + * Creates or finds a MediaStreamingStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding MediaStreamingStatus. + */ + @JsonCreator + public static MediaStreamingStatus fromString(String name) { + return fromString(name, MediaStreamingStatus.class); + } + + /** @return known MediaStreamingStatus values. */ + public static Collection values() { + return values(MediaStreamingStatus.class); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStatusDetails.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStatusDetails.java new file mode 100644 index 0000000000000..93430c0d45f5a --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStatusDetails.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.communication.callautomation.implementation.models; + +import com.azure.core.util.ExpandableStringEnum; +import com.fasterxml.jackson.annotation.JsonCreator; +import java.util.Collection; + +/** Defines values for MediaStreamingStatusDetails. */ +public final class MediaStreamingStatusDetails extends ExpandableStringEnum { + /** Static value subscriptionStarted for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SUBSCRIPTION_STARTED = fromString("subscriptionStarted"); + + /** Static value streamConnectionReestablished for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails STREAM_CONNECTION_REESTABLISHED = + fromString("streamConnectionReestablished"); + + /** Static value streamConnectionUnsuccessful for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails STREAM_CONNECTION_UNSUCCESSFUL = + fromString("streamConnectionUnsuccessful"); + + /** Static value streamUrlMissing for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails STREAM_URL_MISSING = fromString("streamUrlMissing"); + + /** Static value serviceShutdown for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SERVICE_SHUTDOWN = fromString("serviceShutdown"); + + /** Static value streamConnectionInterrupted for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails STREAM_CONNECTION_INTERRUPTED = + fromString("streamConnectionInterrupted"); + + /** Static value speechServicesConnectionError for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SPEECH_SERVICES_CONNECTION_ERROR = + fromString("speechServicesConnectionError"); + + /** Static value subscriptionStopped for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SUBSCRIPTION_STOPPED = fromString("subscriptionStopped"); + + /** Static value unspecifiedError for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails UNSPECIFIED_ERROR = fromString("unspecifiedError"); + + /** Static value authenticationFailure for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails AUTHENTICATION_FAILURE = fromString("authenticationFailure"); + + /** Static value badRequest for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails BAD_REQUEST = fromString("badRequest"); + + /** Static value tooManyRequests for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails TOO_MANY_REQUESTS = fromString("tooManyRequests"); + + /** Static value forbidden for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails FORBIDDEN = fromString("forbidden"); + + /** Static value serviceTimeout for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SERVICE_TIMEOUT = fromString("serviceTimeout"); + + /** Static value initialWebSocketConnectionFailed for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails INITIAL_WEB_SOCKET_CONNECTION_FAILED = + fromString("initialWebSocketConnectionFailed"); + + /** + * Creates or finds a MediaStreamingStatusDetails from its string representation. + * + * @param name a name to look for. + * @return the corresponding MediaStreamingStatusDetails. + */ + @JsonCreator + public static MediaStreamingStatusDetails fromString(String name) { + return fromString(name, MediaStreamingStatusDetails.class); + } + + /** @return known MediaStreamingStatusDetails values. */ + public static Collection values() { + return values(MediaStreamingStatusDetails.class); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStopped.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStopped.java new file mode 100644 index 0000000000000..95390daa30f2a --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingStopped.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.communication.callautomation.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** The MediaStreamingStopped model. */ +@Immutable +public final class MediaStreamingStopped { + /* + * Used by customers when calling mid-call actions to correlate the request + * to the response event. + */ + @JsonProperty(value = "operationContext", access = JsonProperty.Access.WRITE_ONLY) + private String operationContext; + + /* + * Contains the resulting SIP code, sub-code and message. + */ + @JsonProperty(value = "resultInformation", access = JsonProperty.Access.WRITE_ONLY) + private ResultInformation resultInformation; + + /* + * Defines the result for audio streaming update with the current status + * and the details about the status + */ + @JsonProperty(value = "mediaStreamingUpdate", access = JsonProperty.Access.WRITE_ONLY) + private MediaStreamingUpdate mediaStreamingUpdate; + + /* + * Call connection ID. + */ + @JsonProperty(value = "callConnectionId", access = JsonProperty.Access.WRITE_ONLY) + private String callConnectionId; + + /* + * Server call ID. + */ + @JsonProperty(value = "serverCallId", access = JsonProperty.Access.WRITE_ONLY) + private String serverCallId; + + /* + * Correlation ID for event to call correlation. Also called ChainId for + * skype chain ID. + */ + @JsonProperty(value = "correlationId", access = JsonProperty.Access.WRITE_ONLY) + private String correlationId; + + /** + * Get the operationContext property: Used by customers when calling mid-call actions to correlate the request to + * the response event. + * + * @return the operationContext value. + */ + public String getOperationContext() { + return this.operationContext; + } + + /** + * Get the resultInformation property: Contains the resulting SIP code, sub-code and message. + * + * @return the resultInformation value. + */ + public ResultInformation getResultInformation() { + return this.resultInformation; + } + + /** + * Get the mediaStreamingUpdate property: Defines the result for audio streaming update with the current status and + * the details about the status. + * + * @return the mediaStreamingUpdate value. + */ + public MediaStreamingUpdate getMediaStreamingUpdate() { + return this.mediaStreamingUpdate; + } + + /** + * Get the callConnectionId property: Call connection ID. + * + * @return the callConnectionId value. + */ + public String getCallConnectionId() { + return this.callConnectionId; + } + + /** + * Get the serverCallId property: Server call ID. + * + * @return the serverCallId value. + */ + public String getServerCallId() { + return this.serverCallId; + } + + /** + * Get the correlationId property: Correlation ID for event to call correlation. Also called ChainId for skype chain + * ID. + * + * @return the correlationId value. + */ + public String getCorrelationId() { + return this.correlationId; + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingUpdate.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingUpdate.java new file mode 100644 index 0000000000000..e3b2347475b05 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/MediaStreamingUpdate.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.communication.callautomation.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** The MediaStreamingUpdate model. */ +@Fluent +public final class MediaStreamingUpdate { + /* + * The contentType property. + */ + @JsonProperty(value = "contentType") + private String contentType; + + /* + * The mediaStreamingStatus property. + */ + @JsonProperty(value = "mediaStreamingStatus") + private MediaStreamingStatus mediaStreamingStatus; + + /* + * The mediaStreamingStatusDetails property. + */ + @JsonProperty(value = "mediaStreamingStatusDetails") + private MediaStreamingStatusDetails mediaStreamingStatusDetails; + + /** + * Get the contentType property: The contentType property. + * + * @return the contentType value. + */ + public String getContentType() { + return this.contentType; + } + + /** + * Set the contentType property: The contentType property. + * + * @param contentType the contentType value to set. + * @return the MediaStreamingUpdate object itself. + */ + public MediaStreamingUpdate setContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get the mediaStreamingStatus property: The mediaStreamingStatus property. + * + * @return the mediaStreamingStatus value. + */ + public MediaStreamingStatus getMediaStreamingStatus() { + return this.mediaStreamingStatus; + } + + /** + * Set the mediaStreamingStatus property: The mediaStreamingStatus property. + * + * @param mediaStreamingStatus the mediaStreamingStatus value to set. + * @return the MediaStreamingUpdate object itself. + */ + public MediaStreamingUpdate setMediaStreamingStatus(MediaStreamingStatus mediaStreamingStatus) { + this.mediaStreamingStatus = mediaStreamingStatus; + return this; + } + + /** + * Get the mediaStreamingStatusDetails property: The mediaStreamingStatusDetails property. + * + * @return the mediaStreamingStatusDetails value. + */ + public MediaStreamingStatusDetails getMediaStreamingStatusDetails() { + return this.mediaStreamingStatusDetails; + } + + /** + * Set the mediaStreamingStatusDetails property: The mediaStreamingStatusDetails property. + * + * @param mediaStreamingStatusDetails the mediaStreamingStatusDetails value to set. + * @return the MediaStreamingUpdate object itself. + */ + public MediaStreamingUpdate setMediaStreamingStatusDetails( + MediaStreamingStatusDetails mediaStreamingStatusDetails) { + this.mediaStreamingStatusDetails = mediaStreamingStatusDetails; + return this; + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/TransferToParticipantRequestInternal.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/TransferToParticipantRequestInternal.java index cfd9adeb87941..86a8824032e95 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/TransferToParticipantRequestInternal.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/TransferToParticipantRequestInternal.java @@ -44,6 +44,13 @@ public final class TransferToParticipantRequestInternal { @JsonProperty(value = "operationCallbackUri") private String operationCallbackUri; + /* + * The source caller Id, a phone number, that's will be used as the + * transferor's(Contoso) caller id when transfering a call a pstn target. + */ + @JsonProperty(value = "sourceCallerIdNumber") + private PhoneNumberIdentifierModel sourceCallerIdNumber; + /** * Get the targetParticipant property: The identity of the target where call should be transferred to. * @@ -149,4 +156,27 @@ public TransferToParticipantRequestInternal setOperationCallbackUri(String opera this.operationCallbackUri = operationCallbackUri; return this; } + + /** + * Get the sourceCallerIdNumber property: The source caller Id, a phone number, that's will be used as the + * transferor's(Contoso) caller id when transfering a call a pstn target. + * + * @return the sourceCallerIdNumber value. + */ + public PhoneNumberIdentifierModel getSourceCallerIdNumber() { + return this.sourceCallerIdNumber; + } + + /** + * Set the sourceCallerIdNumber property: The source caller Id, a phone number, that's will be used as the + * transferor's(Contoso) caller id when transfering a call a pstn target. + * + * @param sourceCallerIdNumber the sourceCallerIdNumber value to set. + * @return the TransferToParticipantRequestInternal object itself. + */ + public TransferToParticipantRequestInternal setSourceCallerIdNumber( + PhoneNumberIdentifierModel sourceCallerIdNumber) { + this.sourceCallerIdNumber = sourceCallerIdNumber; + return this; + } } diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/AnswerCallOptions.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/AnswerCallOptions.java index 7379cb7675fc0..93fd073df332e 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/AnswerCallOptions.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/AnswerCallOptions.java @@ -3,7 +3,6 @@ package com.azure.communication.callautomation.models; -import com.azure.communication.common.PhoneNumberIdentifier; import com.azure.core.annotation.Fluent; /** @@ -40,12 +39,6 @@ public final class AnswerCallOptions { * The operational context */ private String operationContext; - - /** - * The source caller ID number which is a phone number that will be used when inviting a pstn target. - * Required only when this is an incoming voip call and there will be a transfer call request to a PSTN target. - */ - private PhoneNumberIdentifier sourceCallerIdNumber; /** * Constructor @@ -94,15 +87,6 @@ public String getOperationContext() { return operationContext; } - /** - * Get the sourceCallerIdNumber. - * - * @return the sourceCallerIdNumber - */ - public PhoneNumberIdentifier getSourceCallerIdNumber() { - return sourceCallerIdNumber; - } - /** * Set the transcription configuration. * @@ -124,18 +108,7 @@ public AnswerCallOptions setOperationContext(String operationContext) { this.operationContext = operationContext; return this; } - - /** - * Set the sourceCallerIdNumber. - * - * @param sourceCallerIdNumber the sourceCallerIdNumber to set - * @return the AnswerCallOptions object itself. - */ - public AnswerCallOptions setSourceCallerIdNumber(PhoneNumberIdentifier sourceCallerIdNumber) { - this.sourceCallerIdNumber = sourceCallerIdNumber; - return this; - } - + /** * Get the CallIntelligenceOptions property: AI options for the call such as cognitiveServicesEndpoint * diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/CallInvite.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/CallInvite.java index 89c65abdeb84d..c483a9447a9aa 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/CallInvite.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/CallInvite.java @@ -7,6 +7,7 @@ import com.azure.communication.common.CommunicationIdentifier; import com.azure.communication.common.CommunicationUserIdentifier; +import com.azure.communication.common.MicrosoftTeamsAppIdentifier; import com.azure.communication.common.MicrosoftTeamsUserIdentifier; import com.azure.communication.common.PhoneNumberIdentifier; import com.azure.core.annotation.Fluent; @@ -53,7 +54,17 @@ public CallInvite(MicrosoftTeamsUserIdentifier targetIdentity) { this.sourceCallerIdNumber = null; this.customCallingContext = new CustomCallingContext(null, new HashMap<>()); } - + + /** + * Create a CallInvite object with MicrosoftTeamsAppIdentifier + * @param targetIdentity Target's MicrosoftTeamsAppIdentifier + */ + public CallInvite(MicrosoftTeamsAppIdentifier targetIdentity) { + this.targetParticipant = targetIdentity; + this.sourceCallerIdNumber = null; + this.customCallingContext = new CustomCallingContext(null, new HashMap<>()); + } + /** * Get target's CommunicationIdentifier * @return target's CommunicationIdentifier diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/StartHoldMusicOptions.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/StartHoldMusicOptions.java index 1ef9f5dc1364e..121a0ab4b8337 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/StartHoldMusicOptions.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/StartHoldMusicOptions.java @@ -20,11 +20,6 @@ public class StartHoldMusicOptions { */ private final PlaySource playSourceInfo; - /** - * If Audio will loop. Default is true. - */ - private boolean loop; - /** * Operation context. */ @@ -38,7 +33,6 @@ public class StartHoldMusicOptions { public StartHoldMusicOptions(CommunicationIdentifier targetParticipant, PlaySource playSourceInfo) { this.targetParticipant = targetParticipant; this.playSourceInfo = playSourceInfo; - loop = true; } /** @@ -57,24 +51,6 @@ public PlaySource getPlaySourceInfo() { return playSourceInfo; } - /** - * Get if the music is in loop. - * @return true for loop, false for play once. - */ - public boolean isLoop() { - return loop; - } - - /** - * Set the value for loop. - * @param loop - boolean. - * @return The StartHoldMusicOptions object. - */ - public StartHoldMusicOptions setLoop(boolean loop) { - this.loop = loop; - return this; - } - /** * Get the operation context. * @return operation context. diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/TransferCallToParticipantOptions.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/TransferCallToParticipantOptions.java index cb74223275f50..3ae194b72f66a 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/TransferCallToParticipantOptions.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/TransferCallToParticipantOptions.java @@ -7,6 +7,7 @@ import com.azure.communication.common.CommunicationIdentifier; import com.azure.communication.common.CommunicationUserIdentifier; +import com.azure.communication.common.MicrosoftTeamsAppIdentifier; import com.azure.communication.common.MicrosoftTeamsUserIdentifier; import com.azure.communication.common.PhoneNumberIdentifier; import com.azure.core.annotation.Fluent; @@ -28,13 +29,17 @@ public final class TransferCallToParticipantOptions { */ private CommunicationIdentifier transferee; - - /** * The operational context */ private String operationContext; + /** + * The source caller ID number which is a phone number that will be used when inviting a pstn target. + * Required only when this is an incoming voip call and there will be a transfer call request to a PSTN target. + */ + private PhoneNumberIdentifier sourceCallerIdNumber; + /** * Constructor * @@ -75,6 +80,16 @@ public TransferCallToParticipantOptions(MicrosoftTeamsUserIdentifier targetParti this.customCallingContext = new CustomCallingContext(null, new HashMap<>()); } + /** + * Constructor + * + * @param targetParticipant {@link MicrosoftTeamsAppIdentifier} contains information for TransferTarget(to whom the call is transferred). + */ + public TransferCallToParticipantOptions(MicrosoftTeamsAppIdentifier targetParticipant) { + this.targetParticipant = targetParticipant; + this.customCallingContext = new CustomCallingContext(null, new HashMap<>()); + } + /** * Get the operationContext. * @@ -151,4 +166,24 @@ public TransferCallToParticipantOptions setOperationCallbackUrl(String operation this.operationCallbackUrl = operationCallbackUrl; return this; } + + /** + * Get the sourceCallerIdNumber. + * + * @return the sourceCallerIdNumber + */ + public PhoneNumberIdentifier getSourceCallerIdNumber() { + return sourceCallerIdNumber; + } + + /** + * Set the sourceCallerIdNumber. + * + * @param sourceCallerIdNumber the sourceCallerIdNumber to set + * @return the TransferCallToParticipantOptions object itself. + */ + public TransferCallToParticipantOptions setSourceCallerIdNumber(PhoneNumberIdentifier sourceCallerIdNumber) { + this.sourceCallerIdNumber = sourceCallerIdNumber; + return this; + } } diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingFailed.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingFailed.java new file mode 100644 index 0000000000000..19d03128d6a64 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingFailed.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.communication.callautomation.models.events; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** The MediaStreamingFailed model. */ +@Fluent +public final class MediaStreamingFailed extends CallAutomationEventBase { + + /* + * Contains the resulting SIP code, sub-code and message. + */ + @JsonProperty(value = "resultInformation", access = JsonProperty.Access.WRITE_ONLY) + private ResultInformation resultInformation; + + /* + * Defines the result for audio streaming update with the current status + * and the details about the status + */ + @JsonProperty(value = "mediaStreamingUpdate", access = JsonProperty.Access.WRITE_ONLY) + private MediaStreamingUpdate mediaStreamingUpdateResult; + + /** + * Creates an instance of MediaStreamingFailed class. + */ + public MediaStreamingFailed() { + resultInformation = null; + mediaStreamingUpdateResult = null; + } + + /** + * Get the resultInformation property: Contains the resulting SIP code, sub-code and message. + * + * @return the resultInformation value. + */ + public ResultInformation getResultInformation() { + return this.resultInformation; + } + + /** + * Get the mediaStreamingUpdateResult property: Defines the result for audio streaming update with the current status and + * the details about the status. + * + * @return the mediaStreamingUpdate value. + */ + public MediaStreamingUpdate getMediaStreamingUpdateResult() { + return this.mediaStreamingUpdateResult; + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStarted.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStarted.java new file mode 100644 index 0000000000000..42514e38512b9 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStarted.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.communication.callautomation.models.events; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The MediaStreamingStarted model. + */ +@Fluent +public final class MediaStreamingStarted extends CallAutomationEventBase { + /* + * Contains the resulting SIP code/sub-code and message from NGC services. + */ + @JsonProperty(value = "resultInformation", access = JsonProperty.Access.WRITE_ONLY) + private final ResultInformation resultInformation; + + /* + * Defines the result for MediaStreamingUpdate with the current status and the details about the status + */ + @JsonProperty(value = "mediaStreamingUpdate", access = JsonProperty.Access.WRITE_ONLY) + private final MediaStreamingUpdate mediaStreamingUpdateResult; + + /** + * Creates an instance of MediaStreamingStarted class. + */ + public MediaStreamingStarted() { + resultInformation = null; + mediaStreamingUpdateResult = null; + } + + /** + * Get the resultInformation property: Contains the resulting SIP code/sub-code and message from NGC services. + * + * @return the resultInformation value. + */ + public ResultInformation getResultInformation() { + return this.resultInformation; + } + + /** + * Get the mediaStreamingUpdateResult property: Defines the result for audio streaming update with the current status + * and the details about the status. + * + * @return the mediaStreamingUpdateResult value. + */ + public MediaStreamingUpdate getMediaStreamingUpdateResult() { + return this.mediaStreamingUpdateResult; + } + +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStatus.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStatus.java new file mode 100644 index 0000000000000..500a49de32512 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStatus.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.communication.callautomation.models.events; + +import com.azure.core.util.ExpandableStringEnum; +import com.fasterxml.jackson.annotation.JsonCreator; +import java.util.Collection; + +/** Defines values for MediaStreamingStatus. */ +public final class MediaStreamingStatus extends ExpandableStringEnum { + /** Static value mediaStreamingStarted for MediaStreamingStatus. */ + public static final MediaStreamingStatus MEDIA_STREAMING_STARTED = fromString("mediaStreamingStarted"); + + /** Static value mediaStreamingFailed for MediaStreamingStatus. */ + public static final MediaStreamingStatus MEDIA_STREAMING_FAILED = fromString("mediaStreamingFailed"); + + /** Static value mediaStreamingStopped for MediaStreamingStatus. */ + public static final MediaStreamingStatus MEDIA_STREAMING_STOPPED = fromString("mediaStreamingStopped"); + + /** Static value unspecifiedError for MediaStreamingStatus. */ + public static final MediaStreamingStatus UNSPECIFIED_ERROR = fromString("unspecifiedError"); + + /** + * Creates or finds a MediaStreamingStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding MediaStreamingStatus. + */ + @JsonCreator + public static MediaStreamingStatus fromString(String name) { + return fromString(name, MediaStreamingStatus.class); + } + + /** @return known MediaStreamingStatus values. */ + public static Collection values() { + return values(MediaStreamingStatus.class); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStatusDetails.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStatusDetails.java new file mode 100644 index 0000000000000..97eb4cf6c6054 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStatusDetails.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.communication.callautomation.models.events; + +import com.azure.core.util.ExpandableStringEnum; +import com.fasterxml.jackson.annotation.JsonCreator; +import java.util.Collection; + +/** Defines values for MediaStreamingStatusDetails. */ +public final class MediaStreamingStatusDetails extends ExpandableStringEnum { + /** Static value subscriptionStarted for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SUBSCRIPTION_STARTED = fromString("subscriptionStarted"); + + /** Static value streamConnectionReestablished for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails STREAM_CONNECTION_REESTABLISHED = + fromString("streamConnectionReestablished"); + + /** Static value streamConnectionUnsuccessful for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails STREAM_CONNECTION_UNSUCCESSFUL = + fromString("streamConnectionUnsuccessful"); + + /** Static value streamUrlMissing for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails STREAM_URL_MISSING = fromString("streamUrlMissing"); + + /** Static value serviceShutdown for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SERVICE_SHUTDOWN = fromString("serviceShutdown"); + + /** Static value streamConnectionInterrupted for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails STREAM_CONNECTION_INTERRUPTED = + fromString("streamConnectionInterrupted"); + + /** Static value speechServicesConnectionError for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SPEECH_SERVICES_CONNECTION_ERROR = + fromString("speechServicesConnectionError"); + + /** Static value subscriptionStopped for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SUBSCRIPTION_STOPPED = fromString("subscriptionStopped"); + + /** Static value unspecifiedError for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails UNSPECIFIED_ERROR = fromString("unspecifiedError"); + + /** Static value authenticationFailure for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails AUTHENTICATION_FAILURE = fromString("authenticationFailure"); + + /** Static value badRequest for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails BAD_REQUEST = fromString("badRequest"); + + /** Static value tooManyRequests for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails TOO_MANY_REQUESTS = fromString("tooManyRequests"); + + /** Static value forbidden for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails FORBIDDEN = fromString("forbidden"); + + /** Static value serviceTimeout for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails SERVICE_TIMEOUT = fromString("serviceTimeout"); + + /** Static value initialWebSocketConnectionFailed for MediaStreamingStatusDetails. */ + public static final MediaStreamingStatusDetails INITIAL_WEB_SOCKET_CONNECTION_FAILED = + fromString("initialWebSocketConnectionFailed"); + + /** + * Creates or finds a MediaStreamingStatusDetails from its string representation. + * + * @param name a name to look for. + * @return the corresponding MediaStreamingStatusDetails. + */ + @JsonCreator + public static MediaStreamingStatusDetails fromString(String name) { + return fromString(name, MediaStreamingStatusDetails.class); + } + + /** @return known MediaStreamingStatusDetails values. */ + public static Collection values() { + return values(MediaStreamingStatusDetails.class); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStopped.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStopped.java new file mode 100644 index 0000000000000..4a8e53891eb94 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingStopped.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.communication.callautomation.models.events; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** The MediaStreamingStopped model. */ +@Fluent +public final class MediaStreamingStopped extends CallAutomationEventBase { + + /* + * Contains the resulting SIP code, sub-code and message. + */ + @JsonProperty(value = "resultInformation", access = JsonProperty.Access.WRITE_ONLY) + private ResultInformation resultInformation; + + /* + * Defines the result for audio streaming update with the current status + * and the details about the status + */ + @JsonProperty(value = "mediaStreamingUpdate", access = JsonProperty.Access.WRITE_ONLY) + private MediaStreamingUpdate mediaStreamingUpdateResult; + + /** + * Creates an instance of MediaStreamingStopped class. + */ + public MediaStreamingStopped() { + resultInformation = null; + mediaStreamingUpdateResult = null; + } + + /** + * Get the resultInformation property: Contains the resulting SIP code, sub-code and message. + * + * @return the resultInformation value. + */ + public ResultInformation getResultInformation() { + return this.resultInformation; + } + + /** + * Get the getMediaStreamingUpdateResult property: Defines the result for audio streaming update with the current status and + * the details about the status. + * + * @return the mediaStreamingUpdate value. + */ + public MediaStreamingUpdate getMediaStreamingUpdateResult() { + return this.mediaStreamingUpdateResult; + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingUpdate.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingUpdate.java new file mode 100644 index 0000000000000..b9e094f913f47 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/MediaStreamingUpdate.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.communication.callautomation.models.events; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** The MediaStreamingUpdate model. */ +@Fluent +public final class MediaStreamingUpdate { + /* + * The contentType property. + */ + @JsonProperty(value = "contentType") + private String contentType; + + /* + * The mediaStreamingStatus property. + */ + @JsonProperty(value = "mediaStreamingStatus") + private MediaStreamingStatus mediaStreamingStatus; + + /* + * The mediaStreamingStatusDetails property. + */ + @JsonProperty(value = "mediaStreamingStatusDetails") + private MediaStreamingStatusDetails mediaStreamingStatusDetails; + + /** + * Get the contentType property: The contentType property. + * + * @return the contentType value. + */ + public String getContentType() { + return this.contentType; + } + + /** + * Set the contentType property: The contentType property. + * + * @param contentType the contentType value to set. + * @return the MediaStreamingUpdate object itself. + */ + public MediaStreamingUpdate setContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get the mediaStreamingStatus property: The mediaStreamingStatus property. + * + * @return the mediaStreamingStatus value. + */ + public MediaStreamingStatus getMediaStreamingStatus() { + return this.mediaStreamingStatus; + } + + /** + * Set the mediaStreamingStatus property: The mediaStreamingStatus property. + * + * @param mediaStreamingStatus the mediaStreamingStatus value to set. + * @return the MediaStreamingUpdate object itself. + */ + public MediaStreamingUpdate setMediaStreamingStatus(MediaStreamingStatus mediaStreamingStatus) { + this.mediaStreamingStatus = mediaStreamingStatus; + return this; + } + + /** + * Get the mediaStreamingStatusDetails property: The mediaStreamingStatusDetails property. + * + * @return the mediaStreamingStatusDetails value. + */ + public MediaStreamingStatusDetails getMediaStreamingStatusDetails() { + return this.mediaStreamingStatusDetails; + } + + /** + * Set the mediaStreamingStatusDetails property: The mediaStreamingStatusDetails property. + * + * @param mediaStreamingStatusDetails the mediaStreamingStatusDetails value to set. + * @return the MediaStreamingUpdate object itself. + */ + public MediaStreamingUpdate setMediaStreamingStatusDetails( + MediaStreamingStatusDetails mediaStreamingStatusDetails) { + this.mediaStreamingStatusDetails = mediaStreamingStatusDetails; + return this; + } +} 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 a8efd07874184..27e11915f67f3 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 @@ -11,11 +11,13 @@ import com.azure.communication.callautomation.models.events.CallConnected; import com.azure.communication.callautomation.models.events.CallDisconnected; import com.azure.communication.callautomation.models.events.ParticipantsUpdated; +import com.azure.communication.callautomation.models.events.CreateCallFailed; 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; @@ -31,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( @@ -131,6 +134,7 @@ public void createVOIPCallAndAnswerThenHangupAutomatedTest(HttpClient httpClient } } + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable( @@ -182,13 +186,13 @@ public void createVOIPCallAndRejectAutomatedTest(HttpClient httpClient) { String incomingCallContext = waitForIncomingCallContext(uniqueId, Duration.ofSeconds(10)); assertNotNull(incomingCallContext); - // answer the call + // rejet the call RejectCallOptions rejectCallOptions = new RejectCallOptions(incomingCallContext); receiverAsyncClient.rejectCallWithResponse(rejectCallOptions).block(); // check events - CallDisconnected callDisconnected = waitForEvent(CallDisconnected.class, callerConnectionId, Duration.ofSeconds(10)); - assertNotNull(callDisconnected); + CreateCallFailed createCallFailed = waitForEvent(CreateCallFailed.class, callerConnectionId, Duration.ofSeconds(10)); + assertNotNull(createCallFailed); assertThrows(RuntimeException.class, () -> createCallResult.getCallConnection().getCallProperties()); } catch (Exception ex) { fail("Unexpected exception received", ex); 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 e1b4f6a668907..a7a831b0b173b 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,25 +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 java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; @@ -36,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; @@ -55,8 +61,24 @@ public class CallAutomationAutomatedLiveTestBase extends CallAutomationLiveTestB "https://incomingcalldispatcher.azurewebsites.net"); protected static final String DISPATCHER_CALLBACK = DISPATCHER_ENDPOINT + "/api/servicebuscallback/events"; protected static final String BOT_APP_ID = Configuration.getGlobalConfiguration() - .get("BOT_APP_ID", - "REDACTED-bedb-REDACTED-b8c6-REDACTED"); + .get("BOT_APP_ID", "REDACTED-bedb-REDACTED-b8c6-REDACTED"); + + private static final StringJoiner JSON_PROPERTIES_TO_REDACT + = new StringJoiner("\":\"|\"", "\"", "\":\"") + .add("value") + .add("rawId") + .add("id") + .add("callbackUri") + .add("botAppId") + .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 protected void beforeTest() { @@ -187,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; } @@ -201,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())); } } @@ -241,7 +262,7 @@ protected String waitForIncomingCallContext(String uniqueId, Duration timeOut) t if (incomingCallContext != null) { return incomingCallContext; } - Thread.sleep(1000); + sleepIfRunningAgainstService(1000); } return null; } @@ -256,8 +277,18 @@ 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); + if (!CoreUtils.isNullOrEmpty(captureGroup)) { + content = content.replace(matcher.group(1), "REDACTED"); + } + } + return content; + } } diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationEventParserAndProcessorUnitTests.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationEventParserAndProcessorUnitTests.java index 3c23a7e0c4117..c7c98545a8022 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationEventParserAndProcessorUnitTests.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallAutomationEventParserAndProcessorUnitTests.java @@ -49,6 +49,11 @@ import com.azure.communication.callautomation.models.events.TranscriptionStatusDetails; import com.azure.communication.callautomation.models.events.TranscriptionStopped; import com.azure.communication.callautomation.models.events.TranscriptionUpdated; +import com.azure.communication.callautomation.models.events.MediaStreamingStarted; +import com.azure.communication.callautomation.models.events.MediaStreamingStopped; +import com.azure.communication.callautomation.models.events.MediaStreamingFailed; +import com.azure.communication.callautomation.models.events.MediaStreamingStatus; +import com.azure.communication.callautomation.models.events.MediaStreamingStatusDetails; import org.junit.jupiter.api.Test; import java.util.List; @@ -1426,4 +1431,101 @@ public void parseHoldFailedEvent() { assertEquals(400, holdFailed.getResultInformation().getCode()); assertEquals(ReasonCode.Play.DOWNLOAD_FAILED, holdFailed.getReasonCode()); } + + @Test + public void parseMediaStreamingStartedEvent() { + String receivedEvent = "[{\n" + + "\"id\":\"d13c62c5-721e-44b9-a680-9866c33db7e7\",\n" + + "\"source\":\"calling/callConnections/4c1f5600-a9c6-4343-8979-b638a98de98f\",\n" + + "\"type\":\"Microsoft.Communication.MediaStreamingStarted\",\n" + + "\"data\":{\"eventSource\":\"calling/callConnections/4c1f5600-a9c6-4343-8979-b638a98de98f\",\n" + + "\"operationContext\":\"startMediaStreamingContext\",\n" + + "\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\n" + + "\"mediaStreamingUpdate\":{\"contentType\":\"Audio\",\n" + + "\"mediaStreamingStatus\":\"mediaStreamingStarted\",\n" + + "\"mediaStreamingStatusDetails\":\"subscriptionStarted\"},\n" + + "\"version\":\"2024-06-15-preview\",\n" + + "\"callConnectionId\":\"4c1f5600-a9c6-4343-8979-b638a98de98f\",\n" + + "\"serverCallId\":\"aHR0cHM6Ly9hcGkuZmxpZ2h0cHJveHkuc2t5cGUuY29tL2FwaS92Mi9jcC9jb252LW1hc28tMDEtcHJvZC1ha3MuY29udi5za3lwZS5jb20vY29udi9LTTQteUZBUmhVYXN3T1RqbklPSXZnP2k9MTAtMTI4LTk1LTUyJmU9NjM4NTAwMTgzOTYwNzY2MzQ0\",\n" + + "\"correlationId\":\"30f0ad34-d615-4bf3-8476-5630ae7fc3db\",\n" + + "\"publicEventType\":\"Microsoft.Communication.MediaStreamingStarted\"},\n" + + "\"time\":\"2024-05-02T11:20:42.9110236+00:00\",\n" + + "\"specversion\":\"1.0\",\n" + + "\"datacontenttype\":\"application/json\",\n" + + "\"subject\":\"calling/callConnections/4c1f5600-a9c6-4343-8979-b638a98de98f\"}]"; + + MediaStreamingStarted event = (MediaStreamingStarted) CallAutomationEventParser.parseEvents(receivedEvent).get(0); + assertNotNull(event); + assertEquals("aHR0cHM6Ly9hcGkuZmxpZ2h0cHJveHkuc2t5cGUuY29tL2FwaS92Mi9jcC9jb252LW1hc28tMDEtcHJvZC1ha3MuY29udi5za3lwZS5jb20vY29udi9LTTQteUZBUmhVYXN3T1RqbklPSXZnP2k9MTAtMTI4LTk1LTUyJmU9NjM4NTAwMTgzOTYwNzY2MzQ0", event.getServerCallId()); + assertEquals("4c1f5600-a9c6-4343-8979-b638a98de98f", event.getCallConnectionId()); + assertEquals("30f0ad34-d615-4bf3-8476-5630ae7fc3db", event.getCorrelationId()); + assertEquals("Action completed successfully.", event.getResultInformation().getMessage()); + + assertNotNull(event.getMediaStreamingUpdateResult()); + assertEquals(MediaStreamingStatus.MEDIA_STREAMING_STARTED, event.getMediaStreamingUpdateResult().getMediaStreamingStatus()); + assertEquals(MediaStreamingStatusDetails.SUBSCRIPTION_STARTED, event.getMediaStreamingUpdateResult().getMediaStreamingStatusDetails()); + } + + @Test + public void parseMediaStreamingStoppedEvent() { + String receivedEvent = "[{\n" + + "\"id\":\"41039554-9475-491a-875b-08d23c5d0e75\",\n" + + "\"source\":\"calling/callConnections/4c1f5600-a9c6-4343-8979-b638a98de98f\",\n" + + "\"type\":\"Microsoft.Communication.MediaStreamingStopped\",\n" + + "\"data\":{\"eventSource\":\"calling/callConnections/4c1f5600-a9c6-4343-8979-b638a98de98f\",\n" + + "\"operationContext\":\"startMediaStreamingContext\",\n" + + "\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\n" + + "\"mediaStreamingUpdate\":{\"contentType\":\"Audio\",\"mediaStreamingStatus\":\"mediaStreamingStopped\",\n" + + "\"mediaStreamingStatusDetails\":\"subscriptionStopped\"},\n" + + "\"version\":\"2024-06-15-preview\",\"callConnectionId\":\"4c1f5600-a9c6-4343-8979-b638a98de98f\",\n" + + "\"serverCallId\":\"aHR0cHM6Ly9hcGkuZmxpZ2h0cHJveHkuc2t5cGUuY29tL2FwaS92Mi9jcC9jb252LW1hc28tMDEtcHJvZC1ha3MuY29udi5za3lwZS5jb20vY29udi9LTTQteUZBUmhVYXN3T1RqbklPSXZnP2k9MTAtMTI4LTk1LTUyJmU9NjM4NTAwMTgzOTYwNzY2MzQ0\",\n" + + "\"correlationId\":\"30f0ad34-d615-4bf3-8476-5630ae7fc3db\",\n" + + "\"publicEventType\":\"Microsoft.Communication.MediaStreamingStopped\"},\n" + + "\"time\":\"2024-05-02T11:21:10.0261068+00:00\",\"specversion\":\"1.0\",\n" + + "\"datacontenttype\":\"application/json\",\n" + + "\"subject\":\"calling/callConnections/4c1f5600-a9c6-4343-8979-b638a98de98f\"}]"; + + MediaStreamingStopped event = (MediaStreamingStopped) CallAutomationEventParser.parseEvents(receivedEvent).get(0); + assertNotNull(event); + assertEquals("aHR0cHM6Ly9hcGkuZmxpZ2h0cHJveHkuc2t5cGUuY29tL2FwaS92Mi9jcC9jb252LW1hc28tMDEtcHJvZC1ha3MuY29udi5za3lwZS5jb20vY29udi9LTTQteUZBUmhVYXN3T1RqbklPSXZnP2k9MTAtMTI4LTk1LTUyJmU9NjM4NTAwMTgzOTYwNzY2MzQ0", event.getServerCallId()); + assertEquals("4c1f5600-a9c6-4343-8979-b638a98de98f", event.getCallConnectionId()); + assertEquals("30f0ad34-d615-4bf3-8476-5630ae7fc3db", event.getCorrelationId()); + assertEquals("Action completed successfully.", event.getResultInformation().getMessage()); + + assertNotNull(event.getMediaStreamingUpdateResult()); + assertEquals(MediaStreamingStatus.MEDIA_STREAMING_STOPPED, event.getMediaStreamingUpdateResult().getMediaStreamingStatus()); + assertEquals(MediaStreamingStatusDetails.SUBSCRIPTION_STOPPED, event.getMediaStreamingUpdateResult().getMediaStreamingStatusDetails()); + } + + @Test + public void parseMediaStreamingFailedEvent() { + String receivedEvent = "[{\n" + + "\"id\":\"a9bb7545-8f87-42aa-85d0-d7120dbe2414\",\n" + + "\"source\":\"calling/callConnections/761f5600-43ab-48a0-bbad-ecc5ad5b15bb\",\n" + + "\"type\":\"Microsoft.Communication.MediaStreamingFailed\",\n" + + "\"data\":{\"eventSource\":\"calling/callConnections/761f5600-43ab-48a0-bbad-ecc5ad5b15bb\",\n" + + "\"operationContext\":\"startMediaStreamingContext\",\n" + + "\"resultInformation\":{\"code\":500,\"subCode\":8603,\n" + + "\"message\":\"Action failed, not able to establish websocket connection.\"},\n" + + "\"mediaStreamingUpdate\":{\"contentType\":\"Audio\",\n" + + "\"mediaStreamingStatus\":\"mediaStreamingFailed\",\n" + + "\"mediaStreamingStatusDetails\":\"streamConnectionUnsuccessful\"},\n" + + "\"version\":\"2024-06-15-preview\",\"callConnectionId\":\"761f5600-43ab-48a0-bbad-ecc5ad5b15bb\",\n" + + "\"serverCallId\":\"aHR0cHM6Ly9hcGkuZmxpZ2h0cHJveHkuc2t5cGUuY29tL2FwaS92Mi9jcC9jb252LW1hc28tMDQtcHJvZC1ha3MuY29udi5za3lwZS5jb20vY29udi94MVdMX0p3NnlVaW1aOEkzVi1MN3hnP2k9MTAtMTI4LTg0LTE3MSZlPTYzODQ5NzU2ODQ3MzUxNzU3Mg==\",\n" + + "\"correlationId\":\"6032c474-201d-4ad1-8900-f92a595a6d94\",\n" + + "\"publicEventType\":\"Microsoft.Communication.MediaStreamingFailed\"},\n" + + "\"time\":\"2024-05-02T12:38:31.242039+00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\n" + + "\"subject\":\"calling/callConnections/761f5600-43ab-48a0-bbad-ecc5ad5b15bb\"}]"; + + MediaStreamingFailed event = (MediaStreamingFailed) CallAutomationEventParser.parseEvents(receivedEvent).get(0); + assertNotNull(event); + assertEquals("aHR0cHM6Ly9hcGkuZmxpZ2h0cHJveHkuc2t5cGUuY29tL2FwaS92Mi9jcC9jb252LW1hc28tMDQtcHJvZC1ha3MuY29udi5za3lwZS5jb20vY29udi94MVdMX0p3NnlVaW1aOEkzVi1MN3hnP2k9MTAtMTI4LTg0LTE3MSZlPTYzODQ5NzU2ODQ3MzUxNzU3Mg==", event.getServerCallId()); + assertEquals("761f5600-43ab-48a0-bbad-ecc5ad5b15bb", event.getCallConnectionId()); + assertEquals("6032c474-201d-4ad1-8900-f92a595a6d94", event.getCorrelationId()); + assertEquals("Action failed, not able to establish websocket connection.", event.getResultInformation().getMessage()); + + assertNotNull(event.getMediaStreamingUpdateResult()); + assertEquals(MediaStreamingStatus.MEDIA_STREAMING_FAILED, event.getMediaStreamingUpdateResult().getMediaStreamingStatus()); + assertEquals(MediaStreamingStatusDetails.STREAM_CONNECTION_UNSUCCESSFUL, event.getMediaStreamingUpdateResult().getMediaStreamingStatusDetails()); + } } 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 716181cca5a81..ca45f40b8ebad 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 @@ -11,9 +11,12 @@ import com.azure.core.http.HttpPipelineNextPolicy; import com.azure.core.http.HttpResponse; import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.models.BodilessMatcher; -import com.azure.core.test.models.CustomMatcher; +import com.azure.core.test.InterceptorManager; import com.azure.core.test.TestMode; +import com.azure.core.test.models.TestProxyRequestMatcher; +import com.azure.core.test.models.TestProxySanitizer; +import com.azure.core.test.models.TestProxySanitizerType; +import com.azure.core.test.models.TestProxyRequestMatcher.TestProxyRequestMatcherType; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -21,12 +24,8 @@ import java.time.OffsetDateTime; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import java.util.StringJoiner; -import java.util.function.Function; import java.util.regex.Matcher; -import java.util.regex.Pattern; public class CallAutomationLiveTestBase extends TestProxyTestBase { protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() @@ -62,19 +61,7 @@ public class CallAutomationLiveTestBase extends TestProxyTestBase { .get("TARGET_PHONE_NUMBER", "+16471234567"); protected static final String MEDIA_SOURCE = Configuration.getGlobalConfiguration() .get("ACS_MEDIA_SOURCE", "https://contoso.com/music.wav"); - private static final StringJoiner JSON_PROPERTIES_TO_REDACT - = new StringJoiner("\":\"|\"", "\"", "\":\"") - .add("value") - .add("rawId") - .add("id") - .add("callbackUri") - .add("botAppId") - .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:\\/\\/)([^\\/?]+)"; protected CommunicationIdentityClientBuilder getCommunicationIdentityClientUsingConnectionString(HttpClient httpClient) { CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder() @@ -82,16 +69,9 @@ protected CommunicationIdentityClientBuilder getCommunicationIdentityClientUsing .httpClient(getHttpClientOrUsePlayback(httpClient)); if (getTestMode() == TestMode.RECORD) { - List> redactors = new ArrayList<>(); - redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data))); - builder.addPolicy(interceptorManager.getRecordPolicy(redactors)); - } - - if (interceptorManager.isPlaybackMode()) { - interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), - new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", - "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); + builder.addPolicy(interceptorManager.getRecordPolicy()); } + addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } @@ -110,16 +90,9 @@ protected CallAutomationClientBuilder getCallAutomationClientUsingConnectionStri } if (getTestMode() == TestMode.RECORD) { - List> redactors = new ArrayList<>(); - redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data))); - builder.addPolicy(interceptorManager.getRecordPolicy(redactors)); - } - - if (interceptorManager.isPlaybackMode()) { - interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), - new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", - "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); + builder.addPolicy(interceptorManager.getRecordPolicy()); } + addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } @@ -133,16 +106,9 @@ protected CallAutomationClientBuilder getCallAutomationClientUsingTokenCredentia .httpClient(getHttpClientOrUsePlayback(httpClient)); if (getTestMode() == TestMode.RECORD) { - List> redactors = new ArrayList<>(); - redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data))); - builder.addPolicy(interceptorManager.getRecordPolicy(redactors)); - } - - if (interceptorManager.isPlaybackMode()) { - interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), - new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", - "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); + builder.addPolicy(interceptorManager.getRecordPolicy()); } + addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } @@ -156,16 +122,9 @@ protected CallAutomationClientBuilder getCallAutomationClientUsingInvalidTokenCr .httpClient(getHttpClientOrUsePlayback(httpClient)); if (getTestMode() == TestMode.RECORD) { - List> redactors = new ArrayList<>(); - redactors.add(data -> redact(data, JSON_PROPERTY_VALUE_REDACTION_PATTERN.matcher(data))); - builder.addPolicy(interceptorManager.getRecordPolicy(redactors)); - } - - if (interceptorManager.isPlaybackMode()) { - interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher(), - new CustomMatcher().setHeadersKeyOnlyMatch(Arrays.asList("repeatability-first-sent", - "repeatability-request-id", "x-ms-content-sha256", "x-ms-hmac-string-to-sign-base64")))); + builder.addPolicy(interceptorManager.getRecordPolicy()); } + addTestProxyTestSanitizersAndMatchers(interceptorManager); return builder; } @@ -178,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) { @@ -200,4 +153,41 @@ 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)); + customSanitizers.add(new TestProxySanitizer("x-ms-hmac-string-to-sign-base64", null, "REDACTED", TestProxySanitizerType.HEADER)); + customSanitizers.add(new TestProxySanitizer("MS-CV", null, "REDACTED", TestProxySanitizerType.HEADER)); + customSanitizers.add(new TestProxySanitizer("Request-Contex", null, "REDACTED", TestProxySanitizerType.HEADER)); + customSanitizers.add(new TestProxySanitizer("Strict-Transport-Security", null, "REDACTED", TestProxySanitizerType.HEADER)); + customSanitizers.add(new TestProxySanitizer("X-Azure-Ref", null, "REDACTED", TestProxySanitizerType.HEADER)); + customSanitizers.add(new TestProxySanitizer("x-ms-client-request-id", null, "REDACTED", TestProxySanitizerType.HEADER)); + customSanitizers.add(new TestProxySanitizer("Repeatability-First-Sent", null, "REDACTED", TestProxySanitizerType.HEADER)); + customSanitizers.add(new TestProxySanitizer("Repeatability-Request-ID", null, "REDACTED", TestProxySanitizerType.HEADER)); + customSanitizers.add(new TestProxySanitizer("$..id", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); + customSanitizers.add(new TestProxySanitizer("$..rawId", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); + customSanitizers.add(new TestProxySanitizer("$..callbackUri", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); + customSanitizers.add(new TestProxySanitizer("$..incomingCallContext", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); + customSanitizers.add(new TestProxySanitizer("$..message", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); + 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()) { + List customMatcher = new ArrayList<>(); + customMatcher.add(new TestProxyRequestMatcher(TestProxyRequestMatcherType.BODILESS)); + interceptorManager.addMatchers(customMatcher); + } + } } 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 c807992bf2a33..69662ce923376 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 f37ce857bf5c1..4dac2c5d8b310 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,7 +12,9 @@ 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; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -24,12 +26,14 @@ public class CallDialogAsyncAutomatedLiveTests extends CallAutomationAutomatedLiveTestBase { + @DoNotRecord(skipInPlayback = true) @ParameterizedTest @MethodSource("com.azure.core.test.TestBase#getHttpClients") @DisabledIfEnvironmentVariable( named = "SKIP_LIVE_TEST", matches = "(?i)(true)", disabledReason = "Requires environment to be set up") + @Disabled("Disabling this for now as there is service issue with this test case") public void dialogActionInACallAutomatedTest(HttpClient httpClient) { /* Test case:Start and Stop Dialog on ACS to ACS call * 1. create a CallAutomationClient. 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 60e5034b3d1dd..a7d6c8f178870 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 98e6ee0496314..8187e92aaef84 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/java/com/azure/communication/callautomation/CommunicationIdentifierConverterUnitTests.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CommunicationIdentifierConverterUnitTests.java index 8217f7ae5088d..91e4280a89c0c 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CommunicationIdentifierConverterUnitTests.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CommunicationIdentifierConverterUnitTests.java @@ -8,6 +8,7 @@ import com.azure.communication.callautomation.implementation.models.CommunicationIdentifierModel; import com.azure.communication.callautomation.implementation.models.CommunicationIdentifierModelKind; import com.azure.communication.callautomation.implementation.models.CommunicationUserIdentifierModel; +import com.azure.communication.callautomation.implementation.models.MicrosoftTeamsAppIdentifierModel; import com.azure.communication.callautomation.implementation.models.MicrosoftTeamsUserIdentifierModel; import com.azure.communication.callautomation.implementation.models.PhoneNumberIdentifierModel; import com.azure.communication.common.*; @@ -320,6 +321,104 @@ public void convertWithoutKindMicrosoftTeamsUserNoRawId() { } } + + @Test + public void convertWithoutKindMicrosoftTeamsApp() { + MicrosoftTeamsAppIdentifierModel microsoftTeamsAppIdentifierModel = new MicrosoftTeamsAppIdentifierModel() + .setAppId(testTeamsUserId) + .setCloud(CommunicationCloudEnvironmentModel.GCCH); + CommunicationIdentifierModel communicationIdentifierModel = new CommunicationIdentifierModel() + .setMicrosoftTeamsApp(microsoftTeamsAppIdentifierModel) + .setRawId(testTeamsUserId); + + CommunicationIdentifier got = CommunicationIdentifierConverter.convert(communicationIdentifierModel); + + MicrosoftTeamsAppIdentifier expected = new MicrosoftTeamsAppIdentifier(testTeamsUserId, CommunicationCloudEnvironment.GCCH); + + assertNull(communicationIdentifierModel.getKind()); + assertEquals(expected, got); + } + + @Test + public void convertWithKindMicrosoftTeamsApp() { + MicrosoftTeamsAppIdentifierModel microsoftTeamsAppIdentifierModel = new MicrosoftTeamsAppIdentifierModel() + .setAppId(testTeamsUserId) + .setCloud(CommunicationCloudEnvironmentModel.GCCH); + CommunicationIdentifierModel communicationIdentifierModel = new CommunicationIdentifierModel() + .setMicrosoftTeamsApp(microsoftTeamsAppIdentifierModel) + .setKind(CommunicationIdentifierModelKind.MICROSOFT_TEAMS_APP) + .setRawId(testTeamsUserId); + + CommunicationIdentifier got = CommunicationIdentifierConverter.convert(communicationIdentifierModel); + + MicrosoftTeamsAppIdentifier expected = new MicrosoftTeamsAppIdentifier(testTeamsUserId, CommunicationCloudEnvironment.GCCH); + + assertNotNull(communicationIdentifierModel.getKind()); + assertEquals(CommunicationIdentifierModelKind.MICROSOFT_TEAMS_APP, communicationIdentifierModel.getKind()); + assertEquals(expected, got); + } + + @Test + public void convertWithKindMicrosoftTeamsAppNoAppId() { + MicrosoftTeamsAppIdentifierModel microsoftTeamsAppIdentifierModel = new MicrosoftTeamsAppIdentifierModel() + .setCloud(CommunicationCloudEnvironmentModel.GCCH); + CommunicationIdentifierModel communicationIdentifierModel = new CommunicationIdentifierModel() + .setMicrosoftTeamsApp(microsoftTeamsAppIdentifierModel) + .setKind(CommunicationIdentifierModelKind.MICROSOFT_TEAMS_APP) + .setRawId(testTeamsUserId); + + try { + CommunicationIdentifierConverter.convert(communicationIdentifierModel); + } catch (Exception e) { + assert (e instanceof NullPointerException); + } + } + + @Test + public void convertWithoutKindMicrosoftTeamsAppNoAppId() { + MicrosoftTeamsAppIdentifierModel microsoftTeamsAppIdentifierModel = new MicrosoftTeamsAppIdentifierModel() + .setCloud(CommunicationCloudEnvironmentModel.GCCH); + CommunicationIdentifierModel communicationIdentifierModel = new CommunicationIdentifierModel() + .setMicrosoftTeamsApp(microsoftTeamsAppIdentifierModel) + .setRawId(testTeamsUserId); + + try { + CommunicationIdentifierConverter.convert(communicationIdentifierModel); + } catch (Exception e) { + assert (e instanceof NullPointerException); + } + } + + @Test + public void convertWithKindMicrosoftTeamsAppNoCloudEnv() { + MicrosoftTeamsAppIdentifierModel microsoftTeamsAppIdentifierModel = new MicrosoftTeamsAppIdentifierModel() + .setAppId(testTeamsUserId); + CommunicationIdentifierModel communicationIdentifierModel = new CommunicationIdentifierModel() + .setMicrosoftTeamsApp(microsoftTeamsAppIdentifierModel) + .setKind(CommunicationIdentifierModelKind.MICROSOFT_TEAMS_APP) + .setRawId(testTeamsUserId); + + try { + CommunicationIdentifierConverter.convert(communicationIdentifierModel); + } catch (Exception e) { + assert (e instanceof NullPointerException); + } + } + + @Test + public void convertWithoutKindMicrosoftTeamsAppNoCloudEnv() { + MicrosoftTeamsAppIdentifierModel microsoftTeamsAppIdentifierModel = new MicrosoftTeamsAppIdentifierModel() + .setAppId(testTeamsUserId); + CommunicationIdentifierModel communicationIdentifierModel = new CommunicationIdentifierModel() + .setMicrosoftTeamsApp(microsoftTeamsAppIdentifierModel); + + try { + CommunicationIdentifierConverter.convert(communicationIdentifierModel); + } catch (Exception e) { + assert (e instanceof NullPointerException); + } + } + @Test public void convertWithKindUnknownAndRawId() { CommunicationIdentifierModel communicationIdentifierModel = new CommunicationIdentifierModel() 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 e204ec563f025..0000000000000 --- 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\":\"6b301218-78ee-4dfe-b1f9-6af7728f3ddd\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-40ec-484c-b8ef-04e29639496b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6b301218-78ee-4dfe-b1f9-6af7728f3ddd\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:04:50.2440489\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-40ec-484c-b8ef-04e29639496b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6b301218-78ee-4dfe-b1f9-6af7728f3ddd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:04:50.2440489\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-40ec-484c-b8ef-04e29639496b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6b301218-78ee-4dfe-b1f9-6af7728f3ddd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:04:54.0565499\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-40ec-484c-b8ef-04e29639496b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6b301218-78ee-4dfe-b1f9-6af7728f3ddd\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-01-09T21:04:54.5253025\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-40ec-484c-b8ef-04e29639496b\"}]"] \ 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 131f7722d11ec..0000000000000 --- 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\":\"9155ec80-7f4b-456e-a6c4-fd12ecd3e248\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-f684-4d60-a17b-5d99fae7cd67\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-f684-4d60-a17b-5d99fae7cd67\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-f684-4d60-a17b-5d99fae7cd67\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"9155ec80-7f4b-456e-a6c4-fd12ecd3e248\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:05:00.4021471\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-f684-4d60-a17b-5d99fae7cd67\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-f684-4d60-a17b-5d99fae7cd67\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-f684-4d60-a17b-5d99fae7cd67\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-f684-4d60-a17b-5d99fae7cd67\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"9155ec80-7f4b-456e-a6c4-fd12ecd3e248\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:05:00.4021471\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-f684-4d60-a17b-5d99fae7cd67\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-f684-4d60-a17b-5d99fae7cd67\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-f684-4d60-a17b-5d99fae7cd67\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-f684-4d60-a17b-5d99fae7cd67\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"9155ec80-7f4b-456e-a6c4-fd12ecd3e248\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-01-09T21:05:04.6209569\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-f684-4d60-a17b-5d99fae7cd67\"}]"] \ 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 a01696c3d99f9..0000000000000 --- 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\":\"6a07326c-90d0-4643-b7ac-064e85343c00\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-1600-4b88-ae41-447b107c7da3\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-1600-4b88-ae41-447b107c7da3\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-1600-4b88-ae41-447b107c7da3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a07326c-90d0-4643-b7ac-064e85343c00\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:03:49.6210772\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-1600-4b88-ae41-447b107c7da3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-1600-4b88-ae41-447b107c7da3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-1600-4b88-ae41-447b107c7da3\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":0,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-1600-4b88-ae41-447b107c7da3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a07326c-90d0-4643-b7ac-064e85343c00\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:49.6055049\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-1600-4b88-ae41-447b107c7da3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-25c5-49ee-97f1-dfc1d5adc569\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-25c5-49ee-97f1-dfc1d5adc569\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-25c5-49ee-97f1-dfc1d5adc569\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a07326c-90d0-4643-b7ac-064e85343c00\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:03:49.6992769\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-25c5-49ee-97f1-dfc1d5adc569\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-25c5-49ee-97f1-dfc1d5adc569\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-25c5-49ee-97f1-dfc1d5adc569\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-25c5-49ee-97f1-dfc1d5adc569\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a07326c-90d0-4643-b7ac-064e85343c00\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:49.9804571\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-25c5-49ee-97f1-dfc1d5adc569\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-1600-4b88-ae41-447b107c7da3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-1600-4b88-ae41-447b107c7da3\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-1600-4b88-ae41-447b107c7da3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a07326c-90d0-4643-b7ac-064e85343c00\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:50.2148334\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-1600-4b88-ae41-447b107c7da3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-25c5-49ee-97f1-dfc1d5adc569\",\"type\":\"Microsoft.Communication.CancelAddParticipantSucceeded\",\"data\":{\"invitationId\":\"b171db3b-b044-49b6-af37-4220f3f7e131\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-25c5-49ee-97f1-dfc1d5adc569\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a07326c-90d0-4643-b7ac-064e85343c00\",\"publicEventType\":\"Microsoft.Communication.CancelAddParticipantSucceeded\"},\"time\":\"2024-01-09T21:03:54.3398892\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-25c5-49ee-97f1-dfc1d5adc569\"}]"] \ 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 cb6a05006944c..0000000000000 --- 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\":\"6014f303-1f60-4574-8d01-cf5a7094341f\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5bd3-449b-99ef-0addb9892373\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:03:37.7295165\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5bd3-449b-99ef-0addb9892373\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:37.7763901\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-ed5f-4f40-9fe2-314d82459301\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:37.8388914\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-ed5f-4f40-9fe2-314d82459301\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:03:37.8545189\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\"}]","{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-21f4-4c05-bece-27ee91f7633b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:03:41.9326961\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-21f4-4c05-bece-27ee91f7633b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:42.1671211\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"type\":\"Microsoft.Communication.AddParticipantSucceeded\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"participant\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-ed5f-4f40-9fe2-314d82459301\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.AddParticipantSucceeded\"},\"time\":\"2024-01-09T21:03:42.1671211\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5bd3-449b-99ef-0addb9892373\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:42.1826965\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":3,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-ed5f-4f40-9fe2-314d82459301\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:42.1826965\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":4,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-21f4-4c05-bece-27ee91f7633b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:42.7452538\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":5,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5bd3-449b-99ef-0addb9892373\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:42.7921319\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":4,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-ed5f-4f40-9fe2-314d82459301\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:42.7921319\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":5,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-21f4-4c05-bece-27ee91f7633b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:43.3390119\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":5,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5bd3-449b-99ef-0addb9892373\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:43.3702094\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":5,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-ed5f-4f40-9fe2-314d82459301\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:43.3702094\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5bd3-449b-99ef-0addb9892373\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-01-09T21:03:43.7295949\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5bd3-449b-99ef-0addb9892373\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"type\":\"Microsoft.Communication.RemoveParticipantSucceeded\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"participant\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-ed5f-4f40-9fe2-314d82459301\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.RemoveParticipantSucceeded\"},\"time\":\"2024-01-09T21:03:43.7295949\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":6,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-ed5f-4f40-9fe2-314d82459301\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:43.9579949\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-ed5f-4f40-9fe2-314d82459301\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":6,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-21f4-4c05-bece-27ee91f7633b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6014f303-1f60-4574-8d01-cf5a7094341f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:43.9170917\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-21f4-4c05-bece-27ee91f7633b\"}]"] \ 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 5bf11c7494baf..0000000000000 --- 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\":\"2562a164-fbf0-4099-83f4-b2a049955444\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-71a4-4b16-a298-7f58af72e0a3\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-71a4-4b16-a298-7f58af72e0a3\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-71a4-4b16-a298-7f58af72e0a3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"2562a164-fbf0-4099-83f4-b2a049955444\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:03:27.6356923\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-71a4-4b16-a298-7f58af72e0a3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-3534-498b-b532-bc8b74320875\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-3534-498b-b532-bc8b74320875\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-3534-498b-b532-bc8b74320875\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"2562a164-fbf0-4099-83f4-b2a049955444\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:03:27.6981964\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-3534-498b-b532-bc8b74320875\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-71a4-4b16-a298-7f58af72e0a3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-71a4-4b16-a298-7f58af72e0a3\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-71a4-4b16-a298-7f58af72e0a3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"2562a164-fbf0-4099-83f4-b2a049955444\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:27.6825671\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-71a4-4b16-a298-7f58af72e0a3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-3534-498b-b532-bc8b74320875\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-3534-498b-b532-bc8b74320875\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-3534-498b-b532-bc8b74320875\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"2562a164-fbf0-4099-83f4-b2a049955444\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:03:27.6981964\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-3534-498b-b532-bc8b74320875\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-71a4-4b16-a298-7f58af72e0a3\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-71a4-4b16-a298-7f58af72e0a3\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-71a4-4b16-a298-7f58af72e0a3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"2562a164-fbf0-4099-83f4-b2a049955444\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-01-09T21:03:29.182541\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-71a4-4b16-a298-7f58af72e0a3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-3534-498b-b532-bc8b74320875\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-3534-498b-b532-bc8b74320875\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-3534-498b-b532-bc8b74320875\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"2562a164-fbf0-4099-83f4-b2a049955444\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-01-09T21:03:29.2450325\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-3534-498b-b532-bc8b74320875\"}]"] \ 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 f7d14d55d81f2..0000000000000 --- 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\":\"75ebe437-0eb7-4c98-b624-62ced999e1b6\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-b25e-4b2d-8e87-88c0bf87d0a1\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-b25e-4b2d-8e87-88c0bf87d0a1\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-b25e-4b2d-8e87-88c0bf87d0a1\",\"correlationId\":\"75ebe437-0eb7-4c98-b624-62ced999e1b6\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-01-09T21:03:21.7606237\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-b25e-4b2d-8e87-88c0bf87d0a1\"}]"] \ 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 b793c7a2e92c2..0000000000000 --- 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\":\"37cd3dbb-c2f1-41c1-84cb-bbfa0697a090\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":0,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5eaa-4811-a663-151188568d3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"37cd3dbb-c2f1-41c1-84cb-bbfa0697a090\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:04:01.558788\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5eaa-4811-a663-151188568d3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"37cd3dbb-c2f1-41c1-84cb-bbfa0697a090\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:04:01.558788\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-7f1b-46c2-b546-4c6da080daa7\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-7f1b-46c2-b546-4c6da080daa7\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-7f1b-46c2-b546-4c6da080daa7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"37cd3dbb-c2f1-41c1-84cb-bbfa0697a090\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:04:01.6056127\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-7f1b-46c2-b546-4c6da080daa7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-7f1b-46c2-b546-4c6da080daa7\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-7f1b-46c2-b546-4c6da080daa7\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-7f1b-46c2-b546-4c6da080daa7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"37cd3dbb-c2f1-41c1-84cb-bbfa0697a090\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:04:01.6056127\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-7f1b-46c2-b546-4c6da080daa7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5eaa-4811-a663-151188568d3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"37cd3dbb-c2f1-41c1-84cb-bbfa0697a090\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:04:02.1369297\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"type\":\"Microsoft.Communication.DialogStarted\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Success Result\"},\"dialogInputType\":\"powerVirtualAgents\",\"dialogId\":\"92e08834-b6ee-4ede-8956-9fefa27a691c\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5eaa-4811-a663-151188568d3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"37cd3dbb-c2f1-41c1-84cb-bbfa0697a090\",\"publicEventType\":\"Microsoft.Communication.DialogStarted\"},\"time\":\"2024-01-09T21:04:03.6212649\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"type\":\"Microsoft.Communication.DialogSensitivityUpdate\",\"data\":{\"sensitiveMask\":false,\"eventSource\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Success Result\"},\"dialogInputType\":\"powerVirtualAgents\",\"dialogId\":\"92e08834-b6ee-4ede-8956-9fefa27a691c\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5eaa-4811-a663-151188568d3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"37cd3dbb-c2f1-41c1-84cb-bbfa0697a090\",\"publicEventType\":\"Microsoft.Communication.DialogSensitivityUpdate\"},\"time\":\"2024-01-09T21:04:04.0275199\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"type\":\"Microsoft.Communication.DialogCompleted\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Success Result\"},\"dialogInputType\":\"powerVirtualAgents\",\"dialogId\":\"92e08834-b6ee-4ede-8956-9fefa27a691c\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-5eaa-4811-a663-151188568d3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"37cd3dbb-c2f1-41c1-84cb-bbfa0697a090\",\"publicEventType\":\"Microsoft.Communication.DialogCompleted\"},\"time\":\"2024-01-09T21:04:05.4063016\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-5eaa-4811-a663-151188568d3b\"}]"] \ 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 25635242035c3..0000000000000 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/session-records/dtmfActionsInACallAutomatedTest.json +++ /dev/null @@ -1 +0,0 @@ -["[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-1a5c-4011-9f13-1136d4eab647\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-1a5c-4011-9f13-1136d4eab647\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-1a5c-4011-9f13-1136d4eab647\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef86d874-f004-4a85-b378-547c21da1a48\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-01-09T21:04:31.3360183\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-1a5c-4011-9f13-1136d4eab647\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/401f0b00-8e56-4a64-8779-9e5b3b511867\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"eventSource\":\"calling/callConnections/401f0b00-8e56-4a64-8779-9e5b3b511867\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"401f0b00-8e56-4a64-8779-9e5b3b511867\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"f241ddd2-ebad-44df-b8d3-83ecc7c481d3\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-01-09T21:04:31.6328875\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/401f0b00-8e56-4a64-8779-9e5b3b511867\"}]","{\"to\":{\"kind\":\"phoneNumber\",\"rawId\":\"REDACTED\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"from\":{\"kind\":\"phoneNumber\",\"rawId\":\"REDACTED\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"547dded6-2b88-4e4e-9851-e8a8c66d6eab\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-cdb8-40d4-8a81-8a96dba00df7\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-cdb8-40d4-8a81-8a96dba00df7\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-cdb8-40d4-8a81-8a96dba00df7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"547dded6-2b88-4e4e-9851-e8a8c66d6eab\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:34:52.2808004\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-cdb8-40d4-8a81-8a96dba00df7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-cdb8-40d4-8a81-8a96dba00df7\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-cdb8-40d4-8a81-8a96dba00df7\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"phoneNumber\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-cdb8-40d4-8a81-8a96dba00df7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"547dded6-2b88-4e4e-9851-e8a8c66d6eab\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:34:52.3589492\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-cdb8-40d4-8a81-8a96dba00df7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"f814f185-719e-4009-b01f-e1a6c39bf31f\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:34:52.5777085\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"phoneNumber\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"f814f185-719e-4009-b01f-e1a6c39bf31f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:34:52.5777085\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"type\":\"Microsoft.Communication.SendDtmfTonesCompleted\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"f814f185-719e-4009-b01f-e1a6c39bf31f\",\"publicEventType\":\"Microsoft.Communication.SendDtmfTonesCompleted\"},\"time\":\"2024-01-09T21:34:56.9377202\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"type\":\"Microsoft.Communication.ContinuousDtmfRecognitionStopped\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-4eec-4fa4-9d1f-25f1a6321295\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"f814f185-719e-4009-b01f-e1a6c39bf31f\",\"publicEventType\":\"Microsoft.Communication.ContinuousDtmfRecognitionStopped\"},\"time\":\"2024-01-09T21:34:57.48967\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-4eec-4fa4-9d1f-25f1a6321295\"}]"] \ 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 53d7137743f98..0000000000000 --- 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\":\"3c77b30e-2659-4ac7-9823-bf5ba3fd69cb\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-11a8-4208-9b2f-0e0ca42efe11\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-11a8-4208-9b2f-0e0ca42efe11\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-11a8-4208-9b2f-0e0ca42efe11\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3c77b30e-2659-4ac7-9823-bf5ba3fd69cb\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:35:03.7815358\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-11a8-4208-9b2f-0e0ca42efe11\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-11a8-4208-9b2f-0e0ca42efe11\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-11a8-4208-9b2f-0e0ca42efe11\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-11a8-4208-9b2f-0e0ca42efe11\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3c77b30e-2659-4ac7-9823-bf5ba3fd69cb\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:35:03.7972242\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-11a8-4208-9b2f-0e0ca42efe11\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-988b-46ca-a631-d6eda1f73091\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-988b-46ca-a631-d6eda1f73091\",\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-988b-46ca-a631-d6eda1f73091\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3c77b30e-2659-4ac7-9823-bf5ba3fd69cb\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-01-09T21:35:03.84405\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-988b-46ca-a631-d6eda1f73091\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-988b-46ca-a631-d6eda1f73091\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-988b-46ca-a631-d6eda1f73091\",\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false}],\"sequenceNumber\":1,\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-988b-46ca-a631-d6eda1f73091\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3c77b30e-2659-4ac7-9823-bf5ba3fd69cb\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-01-09T21:35:03.9222414\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-988b-46ca-a631-d6eda1f73091\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/421f6900-988b-46ca-a631-d6eda1f73091\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"eventSource\":\"calling/callConnections/421f6900-988b-46ca-a631-d6eda1f73091\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"version\":\"2023-10-03-preview\",\"callConnectionId\":\"421f6900-988b-46ca-a631-d6eda1f73091\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3c77b30e-2659-4ac7-9823-bf5ba3fd69cb\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2024-01-09T21:35:10.1313061\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/421f6900-988b-46ca-a631-d6eda1f73091\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/swagger/README.md b/sdk/communication/azure-communication-callautomation/swagger/README.md index ef67ad58215dd..ac049ef9e06c0 100644 --- a/sdk/communication/azure-communication-callautomation/swagger/README.md +++ b/sdk/communication/azure-communication-callautomation/swagger/README.md @@ -28,7 +28,7 @@ autorest README.md --java --v4 --use=@autorest/java@4.0.20 --use=@autorest/model ``` yaml tag: package-2023-10-03-preview require: - - https://github.com/Azure/azure-rest-api-specs/blob/77d25dd8426c4ba1619d15582a8c9d9b2f6890e8/specification/communication/data-plane/CallAutomation/readme.md + - https://github.com/Azure/azure-rest-api-specs/blob/ebedc156cf07929f3f72e71e5323ecdfa402267d/specification/communication/data-plane/CallAutomation/readme.md java: true output-folder: ../ license-header: MICROSOFT_MIT_SMALL @@ -254,6 +254,9 @@ directive: - remove-model: TranscriptionStopped - remove-model: TranscriptionUpdated - remove-model: TranscriptionFailed +- remove-model: MediaStreamingStarted +- remove-model: MediaStreamingStopped +- remove-model: MediaStreamingFailed ``` diff --git a/sdk/communication/azure-communication-callingserver/pom.xml b/sdk/communication/azure-communication-callingserver/pom.xml index b6000b9e0f8fb..902b761a039aa 100644 --- a/sdk/communication/azure-communication-callingserver/pom.xml +++ b/sdk/communication/azure-communication-callingserver/pom.xml @@ -54,7 +54,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -70,7 +70,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -132,19 +132,19 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -203,7 +203,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 e5cf3dc2817e1..fbfb3defe4249 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 4a397fa5a51f9..732a8df93167d 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/pom.xml b/sdk/communication/azure-communication-chat/pom.xml index da4e82be42582..6ee8c7d49803d 100644 --- a/sdk/communication/azure-communication-chat/pom.xml +++ b/sdk/communication/azure-communication-chat/pom.xml @@ -50,7 +50,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -66,7 +66,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -96,19 +96,19 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 compile com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -161,7 +161,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 89cd18a49ba8a..4bdb19fff1e7b 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 362f2f720f743..74737342374d0 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-common-perf/pom.xml b/sdk/communication/azure-communication-common-perf/pom.xml index 5c3f0c3090df2..6fdd38f13fede 100644 --- a/sdk/communication/azure-communication-common-perf/pom.xml +++ b/sdk/communication/azure-communication-common-perf/pom.xml @@ -39,18 +39,18 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 diff --git a/sdk/communication/azure-communication-common/pom.xml b/sdk/communication/azure-communication-common/pom.xml index 2b5cd65251354..d659d4605d635 100644 --- a/sdk/communication/azure-communication-common/pom.xml +++ b/sdk/communication/azure-communication-common/pom.xml @@ -46,12 +46,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 compile diff --git a/sdk/communication/azure-communication-common/src/main/java/module-info.java b/sdk/communication/azure-communication-common/src/main/java/module-info.java index d3fa25978a023..5e8f0d4b6703f 100644 --- a/sdk/communication/azure-communication-common/src/main/java/module-info.java +++ b/sdk/communication/azure-communication-common/src/main/java/module-info.java @@ -20,7 +20,6 @@ com.azure.communication.rooms, com.azure.communication.callingserver, com.azure.communication.callautomation, - com.azure.communication.networktraversal, com.azure.communication.jobrouter, com.azure.communication.messages; } diff --git a/sdk/communication/azure-communication-email/pom.xml b/sdk/communication/azure-communication-email/pom.xml index a4a9b036d58d2..3bf8ab6c9b7a8 100644 --- a/sdk/communication/azure-communication-email/pom.xml +++ b/sdk/communication/azure-communication-email/pom.xml @@ -55,12 +55,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -78,13 +78,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -96,13 +96,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -154,7 +154,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/communication/azure-communication-identity/pom.xml b/sdk/communication/azure-communication-identity/pom.xml index 8ffb4c7628453..10f28882ed570 100644 --- a/sdk/communication/azure-communication-identity/pom.xml +++ b/sdk/communication/azure-communication-identity/pom.xml @@ -63,7 +63,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -103,31 +103,31 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-http-netty - 1.14.2 + 1.15.0 compile @@ -175,7 +175,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 4a2be505d72a7..0b183b1b4d6a4 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/assets.json b/sdk/communication/azure-communication-jobrouter/assets.json index b31c312f7260d..30f460c18040b 100644 --- a/sdk/communication/azure-communication-jobrouter/assets.json +++ b/sdk/communication/azure-communication-jobrouter/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/communication/azure-communication-jobrouter", - "Tag": "java/communication/azure-communication-jobrouter_b970df9fcf" + "Tag": "java/communication/azure-communication-jobrouter_db1da26178" } diff --git a/sdk/communication/azure-communication-jobrouter/customization/src/main/java/JobRouterSdkCustomization.java b/sdk/communication/azure-communication-jobrouter/customization/src/main/java/JobRouterSdkCustomization.java index f85667b535da3..20deb030d45f3 100644 --- a/sdk/communication/azure-communication-jobrouter/customization/src/main/java/JobRouterSdkCustomization.java +++ b/sdk/communication/azure-communication-jobrouter/customization/src/main/java/JobRouterSdkCustomization.java @@ -3,6 +3,7 @@ import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.type.ClassOrInterfaceType; import org.slf4j.Logger; +import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; @@ -29,6 +30,13 @@ public void customize(LibraryCustomization customization, Logger logger) { addConnectionStringClientMethod(classCustomizationForJobRouterClientBuilder, "JobRouterClientBuilder"); addHttpPipelineAuthPolicyMethod(classCustomizationForJobRouterClientBuilder); updateHttpPipelineMethod(classCustomizationForJobRouterClientBuilder); + + logger.info("Customizing the ScoringRuleOptions class"); + PackageCustomization modelsPackageCustomization = customization.getPackage("com.azure.communication.jobrouter.models"); + ClassCustomization classCustomizationForScoringRuleOptions = modelsPackageCustomization.getClass("ScoringRuleOptions"); + classCustomizationForScoringRuleOptions + .getMethod("setIsBatchScoringEnabled") + .setModifier(Modifier.PRIVATE); } private void addAuthTraits(ClassCustomization classCustomization) { diff --git a/sdk/communication/azure-communication-jobrouter/pom.xml b/sdk/communication/azure-communication-jobrouter/pom.xml index bb6ae294c2358..d9963d1725a3a 100644 --- a/sdk/communication/azure-communication-jobrouter/pom.xml +++ b/sdk/communication/azure-communication-jobrouter/pom.xml @@ -51,7 +51,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -61,7 +61,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 io.projectreactor @@ -72,7 +72,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -102,13 +102,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -167,7 +167,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/implementation/converters/RouterRuleAdapter.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/implementation/converters/RouterRuleAdapter.java index 6aa3187d248bf..cfbc47cbe48f6 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/implementation/converters/RouterRuleAdapter.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/implementation/converters/RouterRuleAdapter.java @@ -49,9 +49,9 @@ public static RouterRuleInternal getRouterRuleInternal(RouterRule routerRule) { } else if (routerRule.getClass() == WebhookRouterRule.class) { WebhookRouterRule webhookRouterRule = (WebhookRouterRule) routerRule; prioritizationRuleInternal = new WebhookRouterRuleInternal() - .setAuthorizationServerUri(webhookRouterRule.getAuthorizationServerUri()) + .setAuthorizationServerUri(webhookRouterRule.getAuthorizationServerUrl()) .setClientCredential(webhookRouterRule.getClientCredential()) - .setWebhookUri(webhookRouterRule.getWebhookUri()); + .setWebhookUri(webhookRouterRule.getWebhookUrl()); } } @@ -75,11 +75,11 @@ public static RouterRuleInternal convertRouterRuleToInternal(RouterRule rule) { return new StaticRouterRuleInternal().setValue(RouterValueAdapter.getValue(((StaticRouterRule) rule).getValue())); } else if (rule instanceof WebhookRouterRule) { WebhookRouterRule webhookRouterRule = (WebhookRouterRule) rule; - return new WebhookRouterRuleInternal().setWebhookUri(webhookRouterRule.getWebhookUri()) + return new WebhookRouterRuleInternal().setWebhookUri(webhookRouterRule.getWebhookUrl()) .setClientCredential(new OAuth2WebhookClientCredential() .setClientId(webhookRouterRule.getClientCredential().getClientId()) .setClientSecret(webhookRouterRule.getClientCredential().getClientSecret())) - .setAuthorizationServerUri(webhookRouterRule.getAuthorizationServerUri()); + .setAuthorizationServerUri(webhookRouterRule.getAuthorizationServerUrl()); } return null; diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/BestWorkerMode.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/BestWorkerMode.java index b57f8c5dd8fac..b3bc0e453a3c0 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/BestWorkerMode.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/BestWorkerMode.java @@ -30,8 +30,14 @@ public final class BestWorkerMode extends DistributionMode { private ScoringRuleOptions scoringRuleOptions; /** Creates an instance of BestWorkerMode class. */ - public BestWorkerMode() { - this.kind = DistributionModeKind.BEST_WORKER; + public BestWorkerMode() {} + + /** + * Returns kind discriminator. + * @return kind. + */ + public DistributionModeKind getKind() { + return DistributionModeKind.BEST_WORKER; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/CancelExceptionAction.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/CancelExceptionAction.java index 584d3ed1ee925..f11eaf39f71c3 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/CancelExceptionAction.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/CancelExceptionAction.java @@ -29,8 +29,14 @@ public final class CancelExceptionAction extends ExceptionAction { private String dispositionCode; /** Creates an instance of CancelExceptionAction class. */ - public CancelExceptionAction() { - this.kind = ExceptionActionKind.CANCEL; + public CancelExceptionAction() {} + + /** + * Returns kind discriminator. + * @return kind. + */ + public ExceptionActionKind getKind() { + return ExceptionActionKind.CANCEL; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ConditionalQueueSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ConditionalQueueSelectorAttachment.java index 556075b6be11b..20c2bff664368 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ConditionalQueueSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ConditionalQueueSelectorAttachment.java @@ -53,7 +53,14 @@ public ConditionalQueueSelectorAttachment( @JsonProperty(value = "queueSelectors") List queueSelectors) { this.condition = condition; this.queueSelectors = queueSelectors; - this.kind = QueueSelectorAttachmentKind.CONDITIONAL; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public QueueSelectorAttachmentKind getKind() { + return QueueSelectorAttachmentKind.CONDITIONAL; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ConditionalWorkerSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ConditionalWorkerSelectorAttachment.java index 8943874127184..4b2bdd1f435da 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ConditionalWorkerSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ConditionalWorkerSelectorAttachment.java @@ -53,7 +53,14 @@ public ConditionalWorkerSelectorAttachment( @JsonProperty(value = "workerSelectors") List workerSelectors) { this.condition = condition; this.workerSelectors = workerSelectors; - this.kind = WorkerSelectorAttachmentKind.CONDITIONAL; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public WorkerSelectorAttachmentKind getKind() { + return WorkerSelectorAttachmentKind.CONDITIONAL; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/DirectMapRouterRule.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/DirectMapRouterRule.java index 2f84d7a71c45a..b2149e4f73d05 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/DirectMapRouterRule.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/DirectMapRouterRule.java @@ -14,7 +14,13 @@ public final class DirectMapRouterRule extends RouterRule { /** Creates an instance of DirectMapRouterRule class. */ - public DirectMapRouterRule() { - this.kind = RouterRuleKind.DIRECT_MAP; + public DirectMapRouterRule() {} + + /** + * Returns kind discriminator. + * @return kind. + */ + public RouterRuleKind getKind() { + return RouterRuleKind.DIRECT_MAP; } } diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/DistributionMode.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/DistributionMode.java index 419c15d7fb708..3b58baf64644a 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/DistributionMode.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/DistributionMode.java @@ -28,7 +28,7 @@ public abstract class DistributionMode { * kind discriminator. */ @JsonProperty(value = "kind") - protected DistributionModeKind kind; + private DistributionModeKind kind; /* * Governs the minimum desired number of active concurrent offers a job can have. @@ -123,7 +123,5 @@ public DistributionMode setBypassSelectors(Boolean bypassSelectors) { * Returns kind discriminator. * @return kind. */ - public DistributionModeKind getKind() { - return this.kind; - } + public abstract DistributionModeKind getKind(); } diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExceptionAction.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExceptionAction.java index ed9e2a0ebb38f..72611486eb36d 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExceptionAction.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExceptionAction.java @@ -3,6 +3,7 @@ // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.communication.jobrouter.models; +import com.azure.core.annotation.Immutable; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; @@ -20,12 +21,13 @@ @JsonSubTypes.Type(name = "manualReclassify", value = ManualReclassifyExceptionAction.class), @JsonSubTypes.Type(name = "reclassify", value = ReclassifyExceptionAction.class) }) +@Immutable public abstract class ExceptionAction { /** * kind discriminator. */ @JsonProperty(value = "kind") - protected ExceptionActionKind kind; + private ExceptionActionKind kind; /** Creates an instance of ExceptionAction class. */ public ExceptionAction() {} @@ -49,7 +51,5 @@ public String getId() { * Returns kind discriminator. * @return kind. */ - public ExceptionActionKind getKind() { - return this.kind; - } + public abstract ExceptionActionKind getKind(); } diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExceptionTrigger.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExceptionTrigger.java index 8bdb47fda3ce9..d9d5327668a07 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExceptionTrigger.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExceptionTrigger.java @@ -3,6 +3,7 @@ // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.communication.jobrouter.models; +import com.azure.core.annotation.Immutable; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; @@ -19,12 +20,13 @@ @JsonSubTypes.Type(name = "queueLength", value = QueueLengthExceptionTrigger.class), @JsonSubTypes.Type(name = "waitTime", value = WaitTimeExceptionTrigger.class) }) +@Immutable public abstract class ExceptionTrigger { /** * kind discriminator. */ @JsonProperty(value = "kind") - protected ExceptionTriggerKind kind; + private ExceptionTriggerKind kind; /** Creates an instance of ExceptionTrigger class. */ public ExceptionTrigger() {} @@ -33,7 +35,5 @@ public ExceptionTrigger() {} * Returns kind discriminator. * @return kind. */ - public ExceptionTriggerKind getKind() { - return this.kind; - } + public abstract ExceptionTriggerKind getKind(); } diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExpressionRouterRule.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExpressionRouterRule.java index 149e4acaf1c8f..944c4a2d63ded 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExpressionRouterRule.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ExpressionRouterRule.java @@ -35,7 +35,14 @@ public final class ExpressionRouterRule extends RouterRule { @JsonCreator public ExpressionRouterRule(@JsonProperty(value = "expression") String expression) { this.expression = expression; - this.kind = RouterRuleKind.EXPRESSION; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public RouterRuleKind getKind() { + return RouterRuleKind.EXPRESSION; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/FunctionRouterRule.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/FunctionRouterRule.java index ada90799bbbb3..ded04cfe37b96 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/FunctionRouterRule.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/FunctionRouterRule.java @@ -35,7 +35,14 @@ public final class FunctionRouterRule extends RouterRule { @JsonCreator public FunctionRouterRule(@JsonProperty(value = "functionUri") String functionUri) { this.functionUri = functionUri; - this.kind = RouterRuleKind.FUNCTION; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public RouterRuleKind getKind() { + return RouterRuleKind.FUNCTION; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/LongestIdleMode.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/LongestIdleMode.java index a107580c4e965..0ca81d91d9dd1 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/LongestIdleMode.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/LongestIdleMode.java @@ -13,8 +13,14 @@ @Fluent public final class LongestIdleMode extends DistributionMode { /** Creates an instance of LongestIdleMode class. */ - public LongestIdleMode() { - this.kind = DistributionModeKind.LONGEST_IDLE; + public LongestIdleMode() {} + + /** + * Returns kind discriminator. + * @return kind. + */ + public DistributionModeKind getKind() { + return DistributionModeKind.LONGEST_IDLE; } /** {@inheritDoc} */ diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ManualReclassifyExceptionAction.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ManualReclassifyExceptionAction.java index df7caef0085f5..c507796f57378 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ManualReclassifyExceptionAction.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ManualReclassifyExceptionAction.java @@ -35,8 +35,14 @@ public final class ManualReclassifyExceptionAction extends ExceptionAction { private List workerSelectors; /** Creates an instance of ManualReclassifyExceptionAction class. */ - public ManualReclassifyExceptionAction() { - this.kind = ExceptionActionKind.MANUAL_RECLASSIFY; + public ManualReclassifyExceptionAction() {} + + /** + * Returns kind discriminator. + * @return kind. + */ + public ExceptionActionKind getKind() { + return ExceptionActionKind.MANUAL_RECLASSIFY; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/PassThroughQueueSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/PassThroughQueueSelectorAttachment.java index c13ad012cdfdb..8423781cf8f74 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/PassThroughQueueSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/PassThroughQueueSelectorAttachment.java @@ -39,7 +39,14 @@ public PassThroughQueueSelectorAttachment( @JsonProperty(value = "labelOperator") LabelOperator labelOperator) { this.key = key; this.labelOperator = labelOperator; - this.kind = QueueSelectorAttachmentKind.PASS_THROUGH; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public QueueSelectorAttachmentKind getKind() { + return QueueSelectorAttachmentKind.PASS_THROUGH; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/PassThroughWorkerSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/PassThroughWorkerSelectorAttachment.java index 3d220b9b084fc..8993e79a71c33 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/PassThroughWorkerSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/PassThroughWorkerSelectorAttachment.java @@ -51,7 +51,14 @@ public PassThroughWorkerSelectorAttachment( @JsonProperty(value = "labelOperator") LabelOperator labelOperator) { this.key = key; this.labelOperator = labelOperator; - this.kind = WorkerSelectorAttachmentKind.PASS_THROUGH; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public WorkerSelectorAttachmentKind getKind() { + return WorkerSelectorAttachmentKind.PASS_THROUGH; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/QueueLengthExceptionTrigger.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/QueueLengthExceptionTrigger.java index 0f43ca81063b9..09ee2a721feb5 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/QueueLengthExceptionTrigger.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/QueueLengthExceptionTrigger.java @@ -29,7 +29,14 @@ public final class QueueLengthExceptionTrigger extends ExceptionTrigger { @JsonCreator public QueueLengthExceptionTrigger(@JsonProperty(value = "threshold") int threshold) { this.threshold = threshold; - this.kind = ExceptionTriggerKind.QUEUE_LENGTH; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public ExceptionTriggerKind getKind() { + return ExceptionTriggerKind.QUEUE_LENGTH; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/QueueSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/QueueSelectorAttachment.java index af36d7317d865..5f17bf9af3d0c 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/QueueSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/QueueSelectorAttachment.java @@ -3,6 +3,7 @@ // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.communication.jobrouter.models; +import com.azure.core.annotation.Immutable; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; @@ -24,12 +25,13 @@ name = "weightedAllocation", value = WeightedAllocationQueueSelectorAttachment.class) }) +@Immutable public abstract class QueueSelectorAttachment { /** * kind discriminator. */ @JsonProperty(value = "kind") - protected QueueSelectorAttachmentKind kind; + private QueueSelectorAttachmentKind kind; /** Creates an instance of QueueSelectorAttachment class. */ public QueueSelectorAttachment() {} @@ -38,7 +40,5 @@ public QueueSelectorAttachment() {} * Returns kind discriminator. * @return kind. */ - public QueueSelectorAttachmentKind getKind() { - return this.kind; - } + public abstract QueueSelectorAttachmentKind getKind(); } diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ReclassifyExceptionAction.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ReclassifyExceptionAction.java index fa2c57edceb4d..9b9ccb17484b2 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ReclassifyExceptionAction.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ReclassifyExceptionAction.java @@ -35,8 +35,14 @@ public final class ReclassifyExceptionAction extends ExceptionAction { private Map labelsToUpsert; /** Creates an instance of ReclassifyExceptionAction class. */ - public ReclassifyExceptionAction() { - this.kind = ExceptionActionKind.RECLASSIFY; + public ReclassifyExceptionAction() {} + + /** + * Returns kind discriminator. + * @return kind. + */ + public ExceptionActionKind getKind() { + return ExceptionActionKind.RECLASSIFY; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RoundRobinMode.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RoundRobinMode.java index c3f6beae9d83e..9b500a1d8c10b 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RoundRobinMode.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RoundRobinMode.java @@ -16,8 +16,14 @@ public final class RoundRobinMode extends DistributionMode { /** Creates an instance of RoundRobinMode class. */ - public RoundRobinMode() { - this.kind = DistributionModeKind.ROUND_ROBIN; + public RoundRobinMode() {} + + /** + * Returns kind discriminator. + * @return kind. + */ + public DistributionModeKind getKind() { + return DistributionModeKind.ROUND_ROBIN; } /** {@inheritDoc} */ diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RouterRule.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RouterRule.java index 0b10a599eb294..bd6b57f5fa073 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RouterRule.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RouterRule.java @@ -3,6 +3,7 @@ // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.communication.jobrouter.models; +import com.azure.core.annotation.Immutable; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; @@ -27,13 +28,14 @@ @JsonSubTypes.Type(name = "static", value = StaticRouterRule.class), @JsonSubTypes.Type(name = "webhook", value = WebhookRouterRule.class) }) +@Immutable public abstract class RouterRule { /** * kind discriminator. */ @JsonProperty(value = "kind") - protected RouterRuleKind kind; + private RouterRuleKind kind; /** Creates an instance of RouterRule class. */ public RouterRule() {} @@ -42,7 +44,5 @@ public RouterRule() {} * Returns kind discriminator. * @return kind. */ - public RouterRuleKind getKind() { - return this.kind; - } + public abstract RouterRuleKind getKind(); } diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RuleEngineQueueSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RuleEngineQueueSelectorAttachment.java index 33953961bc8a8..a17057f471856 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RuleEngineQueueSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RuleEngineQueueSelectorAttachment.java @@ -41,7 +41,14 @@ public final class RuleEngineQueueSelectorAttachment extends QueueSelectorAttach @JsonCreator public RuleEngineQueueSelectorAttachment(@JsonProperty(value = "rule") RouterRule rule) { this.rule = rule; - this.kind = QueueSelectorAttachmentKind.RULE_ENGINE; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public QueueSelectorAttachmentKind getKind() { + return QueueSelectorAttachmentKind.RULE_ENGINE; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RuleEngineWorkerSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RuleEngineWorkerSelectorAttachment.java index dc83330748550..800c8fb25dd86 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RuleEngineWorkerSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/RuleEngineWorkerSelectorAttachment.java @@ -41,7 +41,14 @@ public final class RuleEngineWorkerSelectorAttachment extends WorkerSelectorAtta @JsonCreator public RuleEngineWorkerSelectorAttachment(@JsonProperty(value = "rule") RouterRule rule) { this.rule = rule; - this.kind = WorkerSelectorAttachmentKind.RULE_ENGINE; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public WorkerSelectorAttachmentKind getKind() { + return WorkerSelectorAttachmentKind.RULE_ENGINE; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ScoringRuleOptions.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ScoringRuleOptions.java index 397e403ac5480..81761c95b2ef7 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ScoringRuleOptions.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/ScoringRuleOptions.java @@ -130,20 +130,20 @@ public Boolean isBatchScoringEnabled() { * @param isBatchScoringEnabled the isBatchScoringEnabled value to set. * @return the ScoringRuleOptions object itself. */ - public ScoringRuleOptions setBatchScoringEnabled(Boolean isBatchScoringEnabled) { + private ScoringRuleOptions setIsBatchScoringEnabled(Boolean isBatchScoringEnabled) { this.isBatchScoringEnabled = isBatchScoringEnabled; return this; } /** - * Set the isBatchScoringEnabled property: If set to true, will score workers in batches, and the parameter name of + * Set the isBatchSco ringEnabled property: If set to true, will score workers in batches, and the parameter name of * the worker labels will be sent as `workers`. By default, set to false and the parameter name for the worker * labels will be sent as `worker`. Note: If enabled, use 'batchSize' to set batch size. * * @param isBatchScoringEnabled the isBatchScoringEnabled value to set. - * @return the ScoringRuleOptions object itself. + * @return theScoringRuleOptions object itself. */ - public ScoringRuleOptions setIsBatchScoringEnabled(Boolean isBatchScoringEnabled) { + public ScoringRuleOptions setBatchScoringEnabled(Boolean isBatchScoringEnabled) { this.isBatchScoringEnabled = isBatchScoringEnabled; return this; } diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticQueueSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticQueueSelectorAttachment.java index bedef4ef55891..b5ca011c9c63c 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticQueueSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticQueueSelectorAttachment.java @@ -30,7 +30,14 @@ public final class StaticQueueSelectorAttachment extends QueueSelectorAttachment @JsonCreator public StaticQueueSelectorAttachment(@JsonProperty(value = "queueSelector") RouterQueueSelector queueSelector) { this.queueSelector = queueSelector; - this.kind = QueueSelectorAttachmentKind.STATIC; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public QueueSelectorAttachmentKind getKind() { + return QueueSelectorAttachmentKind.STATIC; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticRouterRule.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticRouterRule.java index ab1bb1a3c6205..a5b64841ca21b 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticRouterRule.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticRouterRule.java @@ -25,8 +25,14 @@ public final class StaticRouterRule extends RouterRule { private RouterValue value; /** Creates an instance of StaticRouterRule class. */ - public StaticRouterRule() { - this.kind = RouterRuleKind.STATIC; + public StaticRouterRule() {} + + /** + * Returns kind discriminator. + * @return kind. + */ + public RouterRuleKind getKind() { + return RouterRuleKind.STATIC; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticWorkerSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticWorkerSelectorAttachment.java index 78974e3651880..ba89d4759a584 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticWorkerSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/StaticWorkerSelectorAttachment.java @@ -30,7 +30,14 @@ public final class StaticWorkerSelectorAttachment extends WorkerSelectorAttachme @JsonCreator public StaticWorkerSelectorAttachment(@JsonProperty(value = "workerSelector") RouterWorkerSelector workerSelector) { this.workerSelector = workerSelector; - this.kind = WorkerSelectorAttachmentKind.STATIC; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public WorkerSelectorAttachmentKind getKind() { + return WorkerSelectorAttachmentKind.STATIC; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WaitTimeExceptionTrigger.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WaitTimeExceptionTrigger.java index a4971b067bc29..d69063683294f 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WaitTimeExceptionTrigger.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WaitTimeExceptionTrigger.java @@ -35,7 +35,14 @@ public final class WaitTimeExceptionTrigger extends ExceptionTrigger { @JsonCreator public WaitTimeExceptionTrigger(@JsonProperty(value = "thresholdSeconds") Duration threshold) { this.threshold = threshold; - this.kind = ExceptionTriggerKind.WAIT_TIME; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public ExceptionTriggerKind getKind() { + return ExceptionTriggerKind.WAIT_TIME; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WebhookRouterRule.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WebhookRouterRule.java index 75ae7a81f8a48..73748be1151c4 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WebhookRouterRule.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WebhookRouterRule.java @@ -17,8 +17,8 @@ public final class WebhookRouterRule extends RouterRule { /* * Uri for Authorization Server. */ - @JsonProperty(value = "authorizationServerUri") - private String authorizationServerUri; + @JsonProperty(value = "authorizationServerUrl") + private String authorizationServerUrl; /* * OAuth2.0 Credentials used to Contoso's Authorization server. Reference: @@ -28,33 +28,39 @@ public final class WebhookRouterRule extends RouterRule { private OAuth2WebhookClientCredential clientCredential; /* - * Uri for Contoso's Web Server. + * Url for Contoso's Web Server. */ - @JsonProperty(value = "webhookUri") - private String webhookUri; + @JsonProperty(value = "webhookUrl") + private String webhookUrl; /** Creates an instance of WebhookRouterRule class. */ - public WebhookRouterRule() { - this.kind = RouterRuleKind.WEBHOOK; + public WebhookRouterRule() {} + + /** + * Returns kind discriminator. + * @return kind. + */ + public RouterRuleKind getKind() { + return RouterRuleKind.WEBHOOK; } /** - * Get the authorizationServerUri property: Uri for Authorization Server. + * Get the authorizationServerUrl property: Url for Authorization Server. * - * @return the authorizationServerUri value. + * @return the authorizationServerUrl value. */ - public String getAuthorizationServerUri() { - return this.authorizationServerUri; + public String getAuthorizationServerUrl() { + return this.authorizationServerUrl; } /** * Set the authorizationServerUri property: Uri for Authorization Server. * - * @param authorizationServerUri the authorizationServerUri value to set. + * @param authorizationServerUrl the authorizationServerUri value to set. * @return the WebhookRouterRule object itself. */ - public WebhookRouterRule setAuthorizationServerUri(String authorizationServerUri) { - this.authorizationServerUri = authorizationServerUri; + public WebhookRouterRule setAuthorizationServerUrl(String authorizationServerUrl) { + this.authorizationServerUrl = authorizationServerUrl; return this; } @@ -71,20 +77,20 @@ public OAuth2WebhookClientCredential getClientCredential() { /** * Get the webhookUri property: Uri for Contoso's Web Server. * - * @return the webhookUri value. + * @return the webhookUrl value. */ - public String getWebhookUri() { - return this.webhookUri; + public String getWebhookUrl() { + return this.getWebhookUrl(); } /** * Set the webhookUri property: Uri for Contoso's Web Server. * - * @param webhookUri the webhookUri value to set. + * @param webhookUrl the webhookUri value to set. * @return the WebhookRouterRule object itself. */ - public WebhookRouterRule setWebhookUri(String webhookUri) { - this.webhookUri = webhookUri; + public WebhookRouterRule setWebhookUrl(String webhookUrl) { + this.webhookUrl = webhookUrl; return this; } diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WeightedAllocationQueueSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WeightedAllocationQueueSelectorAttachment.java index 666b559839099..a2dd2f533cc2a 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WeightedAllocationQueueSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WeightedAllocationQueueSelectorAttachment.java @@ -32,7 +32,14 @@ public final class WeightedAllocationQueueSelectorAttachment extends QueueSelect public WeightedAllocationQueueSelectorAttachment( @JsonProperty(value = "allocations") List allocations) { this.allocations = allocations; - this.kind = QueueSelectorAttachmentKind.WEIGHTED_ALLOCATION; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public QueueSelectorAttachmentKind getKind() { + return QueueSelectorAttachmentKind.WEIGHTED_ALLOCATION; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WeightedAllocationWorkerSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WeightedAllocationWorkerSelectorAttachment.java index 9cdaceac4b01a..5f1a65d69136b 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WeightedAllocationWorkerSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WeightedAllocationWorkerSelectorAttachment.java @@ -32,7 +32,14 @@ public final class WeightedAllocationWorkerSelectorAttachment extends WorkerSele public WeightedAllocationWorkerSelectorAttachment( @JsonProperty(value = "allocations") List allocations) { this.allocations = allocations; - this.kind = WorkerSelectorAttachmentKind.WEIGHTED_ALLOCATION; + } + + /** + * Returns kind discriminator. + * @return kind. + */ + public WorkerSelectorAttachmentKind getKind() { + return WorkerSelectorAttachmentKind.WEIGHTED_ALLOCATION; } /** diff --git a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WorkerSelectorAttachment.java b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WorkerSelectorAttachment.java index 8834c28f447ce..1b8fa463d7a13 100644 --- a/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WorkerSelectorAttachment.java +++ b/sdk/communication/azure-communication-jobrouter/src/main/java/com/azure/communication/jobrouter/models/WorkerSelectorAttachment.java @@ -3,6 +3,7 @@ // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.communication.jobrouter.models; +import com.azure.core.annotation.Immutable; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; @@ -24,12 +25,13 @@ name = "weightedAllocation", value = WeightedAllocationWorkerSelectorAttachment.class) }) +@Immutable public abstract class WorkerSelectorAttachment { /** * kind discriminator. */ @JsonProperty(value = "kind") - protected WorkerSelectorAttachmentKind kind; + private WorkerSelectorAttachmentKind kind; /** Creates an instance of WorkerSelectorAttachment class. */ public WorkerSelectorAttachment() {} @@ -38,7 +40,5 @@ public WorkerSelectorAttachment() {} * Returns kind discriminator. * @return kind. */ - public WorkerSelectorAttachmentKind getKind() { - return this.kind; - } + public abstract WorkerSelectorAttachmentKind getKind(); } 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 b180abf993675..deac224f7551b 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 5639631436e9b..1da46b2b40da8 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 92e21536b1687..ccf6b55c21578 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 23447f8edab1d..2363a4d1228af 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 800d9d47d2f14..4cd77b5ce4271 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 008f0b3a0eea1..b4423b1403e96 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/pom.xml b/sdk/communication/azure-communication-messages/pom.xml index a92a260b18240..cc6e7be55dfaa 100644 --- a/sdk/communication/azure-communication-messages/pom.xml +++ b/sdk/communication/azure-communication-messages/pom.xml @@ -51,7 +51,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -61,7 +61,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -78,13 +78,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -108,13 +108,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -166,7 +166,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 34bfb174ebdea..ebb1ceae39920 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-networktraversal/CHANGELOG.md b/sdk/communication/azure-communication-networktraversal/CHANGELOG.md deleted file mode 100644 index 1d724c457e5f0..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/CHANGELOG.md +++ /dev/null @@ -1,65 +0,0 @@ -# Release History - -## 1.2.0-beta.1 (Unreleased) - -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 1.1.0 (2024-04-11) - -### Breaking Changes -- Please note, this service was shut down on 03/31/2024 and there is no replacement, please read our [retirement notice](https://azure.microsoft.com/updates/retirement-notice-azure-communication-services-network-traversal-turn-public-preview-is-retiring/) for more details. - -## 1.1.0-beta.2 (2022-04-13) - -### Bugs Fixed - -- Set Ttl parameter in the Communication Relay Async client - -### Other Changes - -- Update of azure-core to 1.27.0 -- Update of azure-communication-common to 1.1.2 - -## 1.1.0-beta.1 (2022-03-15) - -### Features Added - -- Added interfaces from `com.azure.core.client.traits` to `CommunicationRelayClientBuilder` -- Added `retryOptions` to `CommunicationRelayClientBuilder` -- Added optional parameter to GetRelayConfiguration to set credential Time-To-Live in seconds of max 48 hours. The default value will be used if given value exceeds it. - -### Breaking Changes - -- Making Ttl part of the options parameter - -## 1.0.0 (2022-02-11) (Deprecated) - -### Features Added - -- Added GetRelayConfigurationOptions with communicationUser and - routeType as parameters when calling getRelayConfiguration and getRelayConfigurationWithResponse - -## 1.0.0-beta.2 (2021-11-18) - -### Features Added - -- Made User Identity an optional parameter when getting a Relay Configuration. -- Added RouteType as optional parameter when getting a Relay Configuration so users can - choose the routing type protocol of the requested Relay Configuration. - -## 1.0.0-beta.1 (2021-09-09) - -The first preview of the Azure Communication Relay Client has the following features: - -- get a relay configuration by creating a CommunicationRelayClient - -### Features Added - -- Added CommunicationRelayClient in preview. -- Added CommunicationRelayClient.getRelayConfiguration in preview. diff --git a/sdk/communication/azure-communication-networktraversal/README.md b/sdk/communication/azure-communication-networktraversal/README.md deleted file mode 100644 index d8df38be3a067..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Azure Communication Network Traversal Package client library for Java - -This service was shut down on 03/31/2024 and there is no replacement, please read our [retirement notice](https://azure.microsoft.com/updates/retirement-notice-azure-communication-services-network-traversal-turn-public-preview-is-retiring/) for more details. - -## Getting started -## Key concepts -## Examples -## Troubleshooting -## Next steps -## Contributing \ No newline at end of file diff --git a/sdk/communication/azure-communication-networktraversal/assets.json b/sdk/communication/azure-communication-networktraversal/assets.json deleted file mode 100644 index c065f2cf8c410..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "java", - "TagPrefix": "java/communication/azure-communication-networktraversal", - "Tag": "java/communication/azure-communication-networktraversal_09d1ceaafd" -} diff --git a/sdk/communication/azure-communication-networktraversal/ci.yml b/sdk/communication/azure-communication-networktraversal/ci.yml deleted file mode 100644 index fb52ca90b7678..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/ci.yml +++ /dev/null @@ -1,36 +0,0 @@ -# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. - -trigger: - branches: - include: - - main - - hotfix/* - - release/* - paths: - include: - - sdk/communication/azure-communication-networktraversal/ - exclude: - - sdk/communication/azure-communication-networktraversal/pom.xml - -pr: - branches: - include: - - main - - feature/* - - hotfix/* - - release/* - paths: - include: - - sdk/communication/azure-communication-networktraversal/ - exclude: - - sdk/communication/azure-communication-networktraversal/pom.xml - -extends: - template: /eng/pipelines/templates/stages/archetype-sdk-client.yml - parameters: - ServiceDirectory: communication - EnableBatchRelease: true - Artifacts: - - name: azure-communication-networktraversal - groupId: com.azure - safeName: azurecommunicationnetworktraversal diff --git a/sdk/communication/azure-communication-networktraversal/pom.xml b/sdk/communication/azure-communication-networktraversal/pom.xml deleted file mode 100644 index 13602f401602e..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/pom.xml +++ /dev/null @@ -1,187 +0,0 @@ - - - - 4.0.0 - - - com.azure - azure-client-sdk-parent - 1.7.0 - ../../parents/azure-client-sdk-parent - - - com.azure - azure-communication-networktraversal - jar - 1.2.0-beta.1 - - Microsoft Azure Network Traversal client library for communication - - Please note, this package has been deprecated and will no longer be maintained after 03/31/2024. - Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. - - - - The MIT License (MIT) - http://opensource.org/licenses/MIT - repo - - - https://github.com/Azure/azure-sdk-for-java - - - - azure-java-build-docs - ${site.url}/site/${project.artifactId} - - - - - https://github.com/Azure/azure-sdk-for-java - scm:git:git@github.com:Azure/azure-sdk-for-java.git - HEAD - - - - 0.70 - 0.40 - false - - - --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - --add-opens com.azure.communication.common/com.azure.communication.common.implementation=ALL-UNNAMED - - - - - - com.azure - azure-core - 1.48.0 - - - com.azure - azure-communication-common - 1.3.2 - - - com.azure - azure-core-http-netty - 1.14.2 - test - - - org.junit.jupiter - junit-jupiter-api - 5.9.3 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.9.3 - test - - - org.junit.jupiter - junit-jupiter-params - 5.9.3 - test - - - io.projectreactor - reactor-test - 3.4.36 - test - - - com.azure - azure-core-test - 1.24.2 - test - - - com.azure - azure-core-http-okhttp - 1.11.20 - test - - - com.azure - azure-core-http-vertx - 1.0.0-beta.17 - test - - - com.azure - azure-identity - 1.12.0 - test - - - com.azure - azure-communication-identity - 1.5.4 - test - - - - - - - org.jacoco - jacoco-maven-plugin - 0.8.12 - - - com/azure/communication/**/models/**/* - com/azure/communication/**/implementation/**/* - - - - - coverage-report - verify - - report - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - 3.4.1 - - - - - com.azure:* - - - - - - - - - - - java12plus - - [12,) - - - - com.azure - azure-core-http-jdk-httpclient - 1.0.0-beta.12 - test - - - - - diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayAsyncClient.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayAsyncClient.java deleted file mode 100644 index 219af84044429..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayAsyncClient.java +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.communication.networktraversal; - -import com.azure.communication.networktraversal.implementation.CommunicationNetworkTraversalClientImpl; -import com.azure.communication.networktraversal.implementation.CommunicationNetworkTraversalsImpl; -import com.azure.communication.networktraversal.models.CommunicationRelayConfiguration; -import com.azure.communication.networktraversal.models.GetRelayConfigurationOptions; -import com.azure.communication.networktraversal.implementation.models.CommunicationRelayConfigurationRequest; -import com.azure.communication.networktraversal.implementation.models.CommunicationErrorResponseException; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.http.rest.Response; -import reactor.core.publisher.Mono; -import com.azure.core.util.FluxUtil; -import static com.azure.core.util.FluxUtil.withContext; -import com.azure.core.util.Context; - -import static com.azure.core.util.FluxUtil.monoError; - -/** - * Asynchronous client interface for Azure Communication Network Traversal - * operations - * - *

Instantiating an asynchronous CommunicationRelayClient

- * - * - *
- * // You can find your endpoint and access key from your resource in the Azure Portal
- * String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";
- * AzureKeyCredential keyCredential = new AzureKeyCredential("<access-key>");
- *
- * CommunicationRelayAsyncClient communicationRelayClient = new CommunicationRelayClientBuilder()
- *     .endpoint(endpoint)
- *     .credential(keyCredential)
- *     .buildAsyncClient();
- * 
- * - *

View {@link CommunicationRelayClientBuilder this} for additional ways to construct the client.

- * - * @see CommunicationRelayClientBuilder - */ -@ServiceClient(builder = CommunicationRelayClientBuilder.class, isAsync = true) -public final class CommunicationRelayAsyncClient { - - private final CommunicationNetworkTraversalsImpl client; - private final ClientLogger logger = new ClientLogger(CommunicationRelayAsyncClient.class); - - CommunicationRelayAsyncClient(CommunicationNetworkTraversalClientImpl communicationNetworkingClient) { - client = communicationNetworkingClient.getCommunicationNetworkTraversals(); - } - - /** - * Gets a Relay Configuration. - * - *

Sample code for getting a relay configuration without parameters

- * - * - *
-     * CommunicationRelayClient communicationRelayClient = createCommunicationNetworkTraversalClient();
-     * CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration();
-     *
-     * System.out.println("Expires on:" + config.getExpiresOn());
-     * List<CommunicationIceServer> iceServers = config.getIceServers();
-     *
-     * for (CommunicationIceServer iceS : iceServers) {
-     *     System.out.println("URLS: " + iceS.getUrls());
-     *     System.out.println("Username: " + iceS.getUsername());
-     *     System.out.println("Credential: " + iceS.getCredential());
-     *     System.out.println("RouteType: " + iceS.getRouteType());
-     * }
-     * 
- * - * - * @return The obtained Communication Relay Configuration. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getRelayConfiguration() { - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - return this.getRelayConfigurationWithResponse(options, null).flatMap(FluxUtil::toMono); - } - - /** - * Gets a Relay Configuration for a CommunicationUserIdentifier. - * - *

Sample code for getting a relay configuration

- * - * - *
-     * CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
-     *
-     * CommunicationUserIdentifier user = communicationIdentityClient.createUser();
-     * System.out.println("User id: " + user.getId());
-     *
-     * GetRelayConfigurationOptions options = new GetRelayConfigurationOptions();
-     * options.setCommunicationUserIdentifier(user);
-     *
-     * CommunicationRelayClient communicationRelayClient = createCommunicationNetworkTraversalClient();
-     * CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(options);
-     *
-     * System.out.println("Expires on:" + config.getExpiresOn());
-     * List<CommunicationIceServer> iceServers = config.getIceServers();
-     *
-     * for (CommunicationIceServer iceS : iceServers) {
-     *     System.out.println("URLS: " + iceS.getUrls());
-     *     System.out.println("Username: " + iceS.getUsername());
-     *     System.out.println("Credential: " + iceS.getCredential());
-     *     System.out.println("RouteType: " + iceS.getRouteType());
-     * }
-     * 
- * - * - * @param options of the GetRelayConfigurationOptions request - * @return The obtained Communication Relay Configuration. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getRelayConfiguration(GetRelayConfigurationOptions options) { - return this.getRelayConfigurationWithResponse(options, null).flatMap(FluxUtil::toMono); - } - - /** - * Gets a Relay Configuration for a CommunicationUserIdentifier given options with response. - * - * @param options of the GetRelayConfigurationOptions request - * @return The obtained Communication Relay Configuration. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getRelayConfigurationWithResponse(GetRelayConfigurationOptions options) { - return withContext(context -> getRelayConfigurationWithResponse(options, null)); - } - - /** - * Gets a Relay Configuration for a CommunicationUserIdentifier given a RouteType with response. - * - * @param options of the GetRelayConfigurationOptions request - * @param context A {@link Context} representing the request context. - * @return The obtained Communication Relay Configuration. - */ - Mono> getRelayConfigurationWithResponse(GetRelayConfigurationOptions options, Context context) { - context = context == null ? Context.NONE : context; - try { - CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); - if (options != null) { - if (options.getCommunicationUserIdentifier() != null) { - body.setId(options.getCommunicationUserIdentifier().getId()); - } - - if (options.getRouteType() != null) { - body.setRouteType(options.getRouteType()); - } - } - return client.issueRelayConfigurationWithResponseAsync(body, context) - .onErrorMap(CommunicationErrorResponseException.class, e -> e); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayClient.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayClient.java deleted file mode 100644 index 785469247b640..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayClient.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.communication.networktraversal; - -import com.azure.communication.networktraversal.models.CommunicationRelayConfiguration; -import com.azure.communication.networktraversal.models.GetRelayConfigurationOptions; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; - -/** - * Synchronous client interface for Communication Service NetworkTraversal operations - * - *

Instantiating a synchronous CommunicationRelayClient

- * - * - *
- * // You can find your endpoint and access key from your resource in the Azure Portal
- * String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";
- * AzureKeyCredential keyCredential = new AzureKeyCredential("<access-key>");
- *
- * CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder()
- *     .endpoint(endpoint)
- *     .credential(keyCredential)
- *     .buildClient();
- * 
- * - *

View {@link CommunicationRelayClientBuilder this} for additional ways to construct the client.

- * - * @see CommunicationRelayClientBuilder - */ -@ServiceClient(builder = CommunicationRelayClientBuilder.class, isAsync = false) -public final class CommunicationRelayClient { - - private final CommunicationRelayAsyncClient client; - private final ClientLogger logger = new ClientLogger(CommunicationRelayClient.class); - - CommunicationRelayClient(CommunicationRelayAsyncClient communicationNetworkingClient) { - client = communicationNetworkingClient; - } - - /** - * Gets a Relay Configuration. - * - * @return The obtained Communication Relay Configuration - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CommunicationRelayConfiguration getRelayConfiguration() { - return client.getRelayConfiguration().block(); - } - - /** - * Gets a Relay Configuration for a CommunicationUserIdentifier. - * - * @param options of the GetRelayConfigurationOptions request - * @return The obtained Communication Relay Configuration - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CommunicationRelayConfiguration getRelayConfiguration(GetRelayConfigurationOptions options) { - return client.getRelayConfiguration(options).block(); - - } - - /** - * Gets a Relay Configuration with response. - * - * @param options of the GetRelayConfigurationOptions request - * @param context A {@link Context} representing the request context. - * @return The obtained Communication Relay Configuration - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getRelayConfigurationWithResponse(GetRelayConfigurationOptions options, Context context) { - Response response = - client.getRelayConfigurationWithResponse(options, context).block(); - - return response; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayClientBuilder.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayClientBuilder.java deleted file mode 100644 index f8d7fa1acf991..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayClientBuilder.java +++ /dev/null @@ -1,419 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.communication.networktraversal; - -import com.azure.communication.common.implementation.CommunicationConnectionString; -import com.azure.communication.common.implementation.HmacAuthenticationPolicy; -import com.azure.communication.networktraversal.implementation.CommunicationNetworkTraversalClientImpl; -import com.azure.communication.networktraversal.implementation.CommunicationNetworkTraversalClientImplBuilder; -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.AzureKeyCredentialTrait; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.ConnectionStringTrait; -import com.azure.core.client.traits.EndpointTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.TokenCredential; -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; -import com.azure.core.http.policy.CookiePolicy; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.RequestIdPolicy; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.builder.ClientBuilderUtil; -import com.azure.core.util.logging.ClientLogger; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * CommunicationRelayClientBuilder that creates CommunicationRelayAsyncClient and CommunicationRelayClient. - * - *

Instantiating a CommunicationRelayClientBuilder

- * - * - *
- * // You can find your endpoint and access key from your resource in the Azure Portal
- * String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";
- * AzureKeyCredential keyCredential = new AzureKeyCredential("<access-key>");
- *
- * CommunicationRelayClientBuilder communicationRelayClientBuilder = new CommunicationRelayClientBuilder()
- *     .endpoint(endpoint)
- *     .credential(keyCredential);
- * 
- * - * - */ -@ServiceClientBuilder(serviceClients = {CommunicationRelayClient.class, CommunicationRelayAsyncClient.class}) -public final class CommunicationRelayClientBuilder implements - AzureKeyCredentialTrait, - ConfigurationTrait, - ConnectionStringTrait, - EndpointTrait, - HttpTrait, - TokenCredentialTrait { - private static final String SDK_NAME = "name"; - private static final String SDK_VERSION = "version"; - - private static final String COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES = - "azure-communication-networktraversal.properties"; - - private final ClientLogger logger = new ClientLogger(CommunicationRelayClientBuilder.class); - private String endpoint; - private AzureKeyCredential azureKeyCredential; - private TokenCredential tokenCredential; - private HttpClient httpClient; - private HttpLogOptions httpLogOptions = new HttpLogOptions(); - private HttpPipeline pipeline; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - private Configuration configuration; - private ClientOptions clientOptions; - private String connectionString; - private final Map properties = CoreUtils.getProperties(COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES); - private final List customPolicies = new ArrayList<>(); - - /** - * Default constructor for CommunicationRelayClientBuilder. - */ - public CommunicationRelayClientBuilder() { - } - - /** - * Set endpoint of the service - * - * @param endpoint url of the service - * @return CommunicationRelayClientBuilder - */ - @Override - public CommunicationRelayClientBuilder endpoint(String endpoint) { - this.endpoint = endpoint; - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * If a pipeline is not supplied, the credential and httpClient fields must be set - *

- * - * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return CommunicationRelayClientBuilder - */ - @Override - public CommunicationRelayClientBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - return this; - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param tokenCredential {@link TokenCredential} used to authorize requests sent to the service. - * @return The updated {@link CommunicationRelayClientBuilder} object. - */ - @Override - public CommunicationRelayClientBuilder credential(TokenCredential tokenCredential) { - this.tokenCredential = tokenCredential; - return this; - } - - /** - * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. - * - * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. - * @return The updated {@link CommunicationRelayClientBuilder} object. - */ - @Override - public CommunicationRelayClientBuilder credential(AzureKeyCredential keyCredential) { - this.azureKeyCredential = keyCredential; - return this; - } - - /** - * Set endpoint and credential to use - * - * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential - * @return CommunicationRelayClientBuilder - */ - @Override - public CommunicationRelayClientBuilder connectionString(String connectionString) { - CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); - String endpoint = connectionStringObject.getEndpoint(); - String accessKey = connectionStringObject.getAccessKey(); - this - .endpoint(endpoint) - .credential(new AzureKeyCredential(accessKey)); - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param httpClient The {@link HttpClient} to use for requests. - * @return CommunicationRelayClientBuilder - */ - @Override - public CommunicationRelayClientBuilder httpClient(HttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param customPolicy A {@link HttpPipelinePolicy pipeline policy}. - * @return CommunicationRelayClientBuilder - */ - @Override - public CommunicationRelayClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { - this.customPolicies.add(customPolicy); - return this; - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * @return The updated {@link CommunicationRelayClientBuilder} object. - * @see HttpClientOptions - */ - @Override - public CommunicationRelayClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - return this; - } - - /** - * Sets the configuration object used to retrieve environment configuration values during building of the client. - * - * @param configuration Configuration store used to retrieve environment configurations. - * @return the updated CommunicationRelayClientBuilder object - */ - @Override - public CommunicationRelayClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * @return the updated CommunicationRelayClientBuilder object - */ - @Override - public CommunicationRelayClientBuilder httpLogOptions(HttpLogOptions logOptions) { - this.httpLogOptions = logOptions; - return this; - } - - /** - * Sets the {@link RetryPolicy} that is used when each request is sent. - *

- * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy User's retry policy applied to each request. - * @return The updated {@link CommunicationRelayClientBuilder} object. - */ - public CommunicationRelayClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated {@link CommunicationRelayClientBuilder} object. - */ - @Override - public CommunicationRelayClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; - } - - /** - * Sets the {@link CommunicationRelayServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, the service version that will be used will be the latest known service - * version based on the version of the client library being used. If no service version is specified, updating to a - * newer version of the client library will have the result of potentially moving to a newer service version. - *

- * Targeting a specific service version may also mean that the service will return an error for newer APIs. - * - * @param version {@link CommunicationRelayServiceVersion} of the service to be used when making requests. - * @return the updated CommunicationRelayClientBuilder object - */ - public CommunicationRelayClientBuilder serviceVersion(CommunicationRelayServiceVersion version) { - return this; - } - - /** - * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, - * RetryPolicy, and CookiePolicy. - * Additional HttpPolicies specified by additionalPolicies will be applied after them - * - * @return CommunicationRelayAsyncClient instance - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public CommunicationRelayAsyncClient buildAsyncClient() { - Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); - return new CommunicationRelayAsyncClient(createServiceImpl()); - } - - /** - * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, - * RetryPolicy, and CookiePolicy. - * Additional HttpPolicies specified by additionalPolicies will be applied after them - * - * @return CommunicationRelayClient instance - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public CommunicationRelayClient buildClient() { - return new CommunicationRelayClient(buildAsyncClient()); - } - - private CommunicationNetworkTraversalClientImpl createServiceImpl() { - - - HttpPipeline builderPipeline = this.pipeline; - if (this.pipeline == null) { - builderPipeline = createHttpPipeline(httpClient, - createHttpPipelineAuthPolicy(), - customPolicies); - } - - CommunicationNetworkTraversalClientImplBuilder clientBuilder = new CommunicationNetworkTraversalClientImplBuilder(); - clientBuilder.endpoint(endpoint) - .pipeline(builderPipeline); - - return clientBuilder.buildClient(); - } - - private HttpPipelinePolicy createHttpPipelineAuthPolicy() { - if (this.tokenCredential != null && this.azureKeyCredential != null) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); - } - if (this.tokenCredential != null) { - return new BearerTokenAuthenticationPolicy( - this.tokenCredential, "https://communication.azure.com//.default"); - } else if (this.azureKeyCredential != null) { - return new HmacAuthenticationPolicy(this.azureKeyCredential); - } else { - throw logger.logExceptionAsError( - new IllegalArgumentException("Missing credential information while building a client.")); - } - } - - private HttpPipeline createHttpPipeline(HttpClient httpClient, - HttpPipelinePolicy authorizationPolicy, - List customPolicies) { - - List policies = new ArrayList(); - applyRequiredPolicies(policies, authorizationPolicy); - - if (customPolicies != null && customPolicies.size() > 0) { - policies.addAll(customPolicies); - } - - return new HttpPipelineBuilder() - .policies(policies.toArray(new HttpPipelinePolicy[0])) - .httpClient(httpClient) - .clientOptions(clientOptions) - .build(); - } - - private void applyRequiredPolicies(List policies, HttpPipelinePolicy authorizationPolicy) { - String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); - String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); - - ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions; - HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; - - String applicationId = null; - if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) { - applicationId = buildClientOptions.getApplicationId(); - } else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) { - applicationId = buildLogOptions.getApplicationId(); - } - - policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); - policies.add(new RequestIdPolicy()); - policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); - policies.add(new CookiePolicy()); - // auth policy is per request, should be after retry - policies.add(authorizationPolicy); - policies.add(new HttpLoggingPolicy(httpLogOptions)); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayServiceVersion.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayServiceVersion.java deleted file mode 100644 index 360251fc57b94..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/CommunicationRelayServiceVersion.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.communication.networktraversal; - -import com.azure.core.util.ServiceVersion; - -/** - * The versions of Communication Relay Service supported by this client library. - */ -public enum CommunicationRelayServiceVersion implements ServiceVersion { - /** - * Service version {@code 2021_10_08}. - */ - V2021_10_08("2021_10_08"); - - private final String version; - - CommunicationRelayServiceVersion(String version) { - - this.version = version; - } - - /** - * {@inheritDoc} - */ - @Override - public String getVersion() { - - return this.version; - } - - /** - * Gets the latest service version supported by this client library - * - * @return the latest {@link CommunicationRelayServiceVersion} - */ - public static CommunicationRelayServiceVersion getLatest() { - - return V2021_10_08; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/CommunicationNetworkTraversalClientImpl.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/CommunicationNetworkTraversalClientImpl.java deleted file mode 100644 index f65fe516ea6f8..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/CommunicationNetworkTraversalClientImpl.java +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.implementation; - -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.CookiePolicy; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; - -/** Initializes a new instance of the CommunicationNetworkTraversalClient type. */ -public final class CommunicationNetworkTraversalClientImpl { - /** The communication resource, for example https://my-resource.communication.azure.com. */ - private final String endpoint; - - /** - * Gets The communication resource, for example https://my-resource.communication.azure.com. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** Api Version. */ - private final String apiVersion; - - /** - * Gets Api Version. - * - * @return the apiVersion value. - */ - public String getApiVersion() { - return this.apiVersion; - } - - /** The HTTP pipeline to send requests through. */ - private final HttpPipeline httpPipeline; - - /** - * Gets The HTTP pipeline to send requests through. - * - * @return the httpPipeline value. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** The serializer to serialize an object into a string. */ - private final SerializerAdapter serializerAdapter; - - /** - * Gets The serializer to serialize an object into a string. - * - * @return the serializerAdapter value. - */ - public SerializerAdapter getSerializerAdapter() { - return this.serializerAdapter; - } - - /** The CommunicationNetworkTraversalsImpl object to access its operations. */ - private final CommunicationNetworkTraversalsImpl communicationNetworkTraversals; - - /** - * Gets the CommunicationNetworkTraversalsImpl object to access its operations. - * - * @return the CommunicationNetworkTraversalsImpl object. - */ - public CommunicationNetworkTraversalsImpl getCommunicationNetworkTraversals() { - return this.communicationNetworkTraversals; - } - - /** - * Initializes an instance of CommunicationNetworkTraversalClient client. - * - * @param endpoint The communication resource, for example https://my-resource.communication.azure.com. - * @param apiVersion Api Version. - */ - CommunicationNetworkTraversalClientImpl(String endpoint, String apiVersion) { - this( - new HttpPipelineBuilder() - .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) - .build(), - JacksonAdapter.createDefaultSerializerAdapter(), - endpoint, - apiVersion); - } - - /** - * Initializes an instance of CommunicationNetworkTraversalClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param endpoint The communication resource, for example https://my-resource.communication.azure.com. - * @param apiVersion Api Version. - */ - CommunicationNetworkTraversalClientImpl(HttpPipeline httpPipeline, String endpoint, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, apiVersion); - } - - /** - * Initializes an instance of CommunicationNetworkTraversalClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param serializerAdapter The serializer to serialize an object into a string. - * @param endpoint The communication resource, for example https://my-resource.communication.azure.com. - * @param apiVersion Api Version. - */ - CommunicationNetworkTraversalClientImpl( - HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String apiVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.endpoint = endpoint; - this.apiVersion = apiVersion; - this.communicationNetworkTraversals = new CommunicationNetworkTraversalsImpl(this); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/CommunicationNetworkTraversalClientImplBuilder.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/CommunicationNetworkTraversalClientImplBuilder.java deleted file mode 100644 index f7d9c8268bda2..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/CommunicationNetworkTraversalClientImplBuilder.java +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.implementation; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.CookiePolicy; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.HttpPolicyProviders; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.Configuration; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** A builder for creating a new instance of the CommunicationNetworkTraversalClient type. */ -@ServiceClientBuilder(serviceClients = {CommunicationNetworkTraversalClientImpl.class}) -public final class CommunicationNetworkTraversalClientImplBuilder { - private static final String SDK_NAME = "name"; - - private static final String SDK_VERSION = "version"; - - private final Map properties = new HashMap<>(); - - /** Create an instance of the CommunicationNetworkTraversalClientImplBuilder. */ - public CommunicationNetworkTraversalClientImplBuilder() { - this.pipelinePolicies = new ArrayList<>(); - } - - /* - * The communication resource, for example - * https://my-resource.communication.azure.com - */ - private String endpoint; - - /** - * Sets The communication resource, for example https://my-resource.communication.azure.com. - * - * @param endpoint the endpoint value. - * @return the CommunicationNetworkTraversalClientImplBuilder. - */ - public CommunicationNetworkTraversalClientImplBuilder endpoint(String endpoint) { - this.endpoint = endpoint; - return this; - } - - /* - * Api Version - */ - private String apiVersion; - - /** - * Sets Api Version. - * - * @param apiVersion the apiVersion value. - * @return the CommunicationNetworkTraversalClientImplBuilder. - */ - public CommunicationNetworkTraversalClientImplBuilder apiVersion(String apiVersion) { - this.apiVersion = apiVersion; - return this; - } - - /* - * The HTTP pipeline to send requests through - */ - private HttpPipeline pipeline; - - /** - * Sets The HTTP pipeline to send requests through. - * - * @param pipeline the pipeline value. - * @return the CommunicationNetworkTraversalClientImplBuilder. - */ - public CommunicationNetworkTraversalClientImplBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - return this; - } - - /* - * The serializer to serialize an object into a string - */ - private SerializerAdapter serializerAdapter; - - /** - * Sets The serializer to serialize an object into a string. - * - * @param serializerAdapter the serializerAdapter value. - * @return the CommunicationNetworkTraversalClientImplBuilder. - */ - public CommunicationNetworkTraversalClientImplBuilder serializerAdapter(SerializerAdapter serializerAdapter) { - this.serializerAdapter = serializerAdapter; - return this; - } - - /* - * The HTTP client used to send the request. - */ - private HttpClient httpClient; - - /** - * Sets The HTTP client used to send the request. - * - * @param httpClient the httpClient value. - * @return the CommunicationNetworkTraversalClientImplBuilder. - */ - public CommunicationNetworkTraversalClientImplBuilder httpClient(HttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - /* - * The configuration store that is used during construction of the service - * client. - */ - private Configuration configuration; - - /** - * Sets The configuration store that is used during construction of the service client. - * - * @param configuration the configuration value. - * @return the CommunicationNetworkTraversalClientImplBuilder. - */ - public CommunicationNetworkTraversalClientImplBuilder configuration(Configuration configuration) { - this.configuration = configuration; - return this; - } - - /* - * The logging configuration for HTTP requests and responses. - */ - private HttpLogOptions httpLogOptions; - - /** - * Sets The logging configuration for HTTP requests and responses. - * - * @param httpLogOptions the httpLogOptions value. - * @return the CommunicationNetworkTraversalClientImplBuilder. - */ - public CommunicationNetworkTraversalClientImplBuilder httpLogOptions(HttpLogOptions httpLogOptions) { - this.httpLogOptions = httpLogOptions; - return this; - } - - /* - * The retry policy that will attempt to retry failed requests, if - * applicable. - */ - private RetryPolicy retryPolicy; - - /** - * Sets The retry policy that will attempt to retry failed requests, if applicable. - * - * @param retryPolicy the retryPolicy value. - * @return the CommunicationNetworkTraversalClientImplBuilder. - */ - public CommunicationNetworkTraversalClientImplBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - return this; - } - - /* - * The list of Http pipeline policies to add. - */ - private final List pipelinePolicies; - - /** - * Adds a custom Http pipeline policy. - * - * @param customPolicy The custom Http pipeline policy to add. - * @return the CommunicationNetworkTraversalClientImplBuilder. - */ - public CommunicationNetworkTraversalClientImplBuilder addPolicy(HttpPipelinePolicy customPolicy) { - pipelinePolicies.add(customPolicy); - return this; - } - - /** - * Builds an instance of CommunicationNetworkTraversalClientImpl with the provided parameters. - * - * @return an instance of CommunicationNetworkTraversalClientImpl. - */ - public CommunicationNetworkTraversalClientImpl buildClient() { - if (apiVersion == null) { - this.apiVersion = "2022-02-01"; - } - if (pipeline == null) { - this.pipeline = createHttpPipeline(); - } - if (serializerAdapter == null) { - this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); - } - CommunicationNetworkTraversalClientImpl client = - new CommunicationNetworkTraversalClientImpl(pipeline, serializerAdapter, endpoint, apiVersion); - return client; - } - - private HttpPipeline createHttpPipeline() { - Configuration buildConfiguration = - (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; - if (httpLogOptions == null) { - httpLogOptions = new HttpLogOptions(); - } - List policies = new ArrayList<>(); - String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); - String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); - policies.add( - new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); - HttpPolicyProviders.addBeforeRetryPolicies(policies); - policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); - policies.add(new CookiePolicy()); - policies.addAll(this.pipelinePolicies); - HttpPolicyProviders.addAfterRetryPolicies(policies); - policies.add(new HttpLoggingPolicy(httpLogOptions)); - HttpPipeline httpPipeline = - new HttpPipelineBuilder() - .policies(policies.toArray(new HttpPipelinePolicy[0])) - .httpClient(httpClient) - .build(); - return httpPipeline; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/CommunicationNetworkTraversalsImpl.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/CommunicationNetworkTraversalsImpl.java deleted file mode 100644 index 18bfe261cf128..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/CommunicationNetworkTraversalsImpl.java +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.implementation; - -import com.azure.communication.networktraversal.implementation.models.CommunicationErrorResponseException; -import com.azure.communication.networktraversal.implementation.models.CommunicationRelayConfigurationRequest; -import com.azure.communication.networktraversal.models.CommunicationRelayConfiguration; -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import reactor.core.publisher.Mono; - -/** An instance of this class provides access to all the operations defined in CommunicationNetworkTraversals. */ -public final class CommunicationNetworkTraversalsImpl { - /** The proxy service used to perform REST calls. */ - private final CommunicationNetworkTraversalsService service; - - /** The service client containing this operation class. */ - private final CommunicationNetworkTraversalClientImpl client; - - /** - * Initializes an instance of CommunicationNetworkTraversalsImpl. - * - * @param client the instance of the service client containing this operation class. - */ - CommunicationNetworkTraversalsImpl(CommunicationNetworkTraversalClientImpl client) { - this.service = - RestProxy.create( - CommunicationNetworkTraversalsService.class, - client.getHttpPipeline(), - client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for CommunicationNetworkTraversalClientCommunicationNetworkTraversals to - * be used by the proxy service to perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "CommunicationNetwork") - public interface CommunicationNetworkTraversalsService { - @Post("/networkTraversal/:issueRelayConfiguration") - @ExpectedResponses({200}) - @UnexpectedResponseExceptionType(CommunicationErrorResponseException.class) - Mono> issueRelayConfiguration( - @HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CommunicationRelayConfigurationRequest body, - @HeaderParam("Accept") String accept, - Context context); - } - - /** - * Issue a configuration for an STUN/TURN server. - * - * @param body Optional request for providing the id and/or route type for the returned relay configuration. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws CommunicationErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a relay configuration containing the STUN/TURN URLs and credentials. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> issueRelayConfigurationWithResponseAsync( - CommunicationRelayConfigurationRequest body) { - final String accept = "application/json"; - return FluxUtil.withContext( - context -> - service.issueRelayConfiguration( - this.client.getEndpoint(), this.client.getApiVersion(), body, accept, context)); - } - - /** - * Issue a configuration for an STUN/TURN server. - * - * @param body Optional request for providing the id and/or route type for the returned relay configuration. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws CommunicationErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a relay configuration containing the STUN/TURN URLs and credentials. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> issueRelayConfigurationWithResponseAsync( - CommunicationRelayConfigurationRequest body, Context context) { - final String accept = "application/json"; - return service.issueRelayConfiguration( - this.client.getEndpoint(), this.client.getApiVersion(), body, accept, context); - } - - /** - * Issue a configuration for an STUN/TURN server. - * - * @param body Optional request for providing the id and/or route type for the returned relay configuration. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws CommunicationErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a relay configuration containing the STUN/TURN URLs and credentials. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono issueRelayConfigurationAsync( - CommunicationRelayConfigurationRequest body) { - return issueRelayConfigurationWithResponseAsync(body) - .flatMap( - (Response res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Issue a configuration for an STUN/TURN server. - * - * @param body Optional request for providing the id and/or route type for the returned relay configuration. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws CommunicationErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a relay configuration containing the STUN/TURN URLs and credentials. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono issueRelayConfigurationAsync( - CommunicationRelayConfigurationRequest body, Context context) { - return issueRelayConfigurationWithResponseAsync(body, context) - .flatMap( - (Response res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Issue a configuration for an STUN/TURN server. - * - * @param body Optional request for providing the id and/or route type for the returned relay configuration. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws CommunicationErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a relay configuration containing the STUN/TURN URLs and credentials. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CommunicationRelayConfiguration issueRelayConfiguration(CommunicationRelayConfigurationRequest body) { - return issueRelayConfigurationAsync(body).block(); - } - - /** - * Issue a configuration for an STUN/TURN server. - * - * @param body Optional request for providing the id and/or route type for the returned relay configuration. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws CommunicationErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a relay configuration containing the STUN/TURN URLs and credentials. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response issueRelayConfigurationWithResponse( - CommunicationRelayConfigurationRequest body, Context context) { - return issueRelayConfigurationWithResponseAsync(body, context).block(); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationError.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationError.java deleted file mode 100644 index 56a4c608f0b34..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationError.java +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.List; - -/** The Communication Services error. */ -@Fluent -public final class CommunicationError { - /* - * The error code. - */ - @JsonProperty(value = "code", required = true) - private String code; - - /* - * The error message. - */ - @JsonProperty(value = "message", required = true) - private String message; - - /* - * The error target. - */ - @JsonProperty(value = "target", access = JsonProperty.Access.WRITE_ONLY) - private String target; - - /* - * Further details about specific errors that led to this error. - */ - @JsonProperty(value = "details", access = JsonProperty.Access.WRITE_ONLY) - private List details; - - /* - * The inner error if any. - */ - @JsonProperty(value = "innererror", access = JsonProperty.Access.WRITE_ONLY) - private CommunicationError innerError; - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - public String getCode() { - return this.code; - } - - /** - * Set the code property: The error code. - * - * @param code the code value to set. - * @return the CommunicationError object itself. - */ - public CommunicationError setCode(String code) { - this.code = code; - return this; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - public String getMessage() { - return this.message; - } - - /** - * Set the message property: The error message. - * - * @param message the message value to set. - * @return the CommunicationError object itself. - */ - public CommunicationError setMessage(String message) { - this.message = message; - return this; - } - - /** - * Get the target property: The error target. - * - * @return the target value. - */ - public String getTarget() { - return this.target; - } - - /** - * Get the details property: Further details about specific errors that led to this error. - * - * @return the details value. - */ - public List getDetails() { - return this.details; - } - - /** - * Get the innerError property: The inner error if any. - * - * @return the innerError value. - */ - public CommunicationError getInnerError() { - return this.innerError; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationErrorResponse.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationErrorResponse.java deleted file mode 100644 index b871b3fcebc4f..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationErrorResponse.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** The Communication Services error. */ -@Fluent -public final class CommunicationErrorResponse { - /* - * The Communication Services error. - */ - @JsonProperty(value = "error", required = true) - private CommunicationError error; - - /** - * Get the error property: The Communication Services error. - * - * @return the error value. - */ - public CommunicationError getError() { - return this.error; - } - - /** - * Set the error property: The Communication Services error. - * - * @param error the error value to set. - * @return the CommunicationErrorResponse object itself. - */ - public CommunicationErrorResponse setError(CommunicationError error) { - this.error = error; - return this; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationErrorResponseException.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationErrorResponseException.java deleted file mode 100644 index 34a49e99f931e..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationErrorResponseException.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.implementation.models; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** Exception thrown for an invalid response with CommunicationErrorResponse information. */ -public final class CommunicationErrorResponseException extends HttpResponseException { - /** - * Initializes a new instance of the CommunicationErrorResponseException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public CommunicationErrorResponseException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the CommunicationErrorResponseException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - * @param value the deserialized response value. - */ - public CommunicationErrorResponseException( - String message, HttpResponse response, CommunicationErrorResponse value) { - super(message, response, value); - } - - @Override - public CommunicationErrorResponse getValue() { - return (CommunicationErrorResponse) super.getValue(); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationRelayConfigurationRequest.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationRelayConfigurationRequest.java deleted file mode 100644 index ab3a1058bbc65..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/CommunicationRelayConfigurationRequest.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.implementation.models; - -import com.azure.communication.networktraversal.models.RouteType; -import com.azure.core.annotation.Fluent; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** Request for a CommunicationRelayConfiguration. */ -@Fluent -public final class CommunicationRelayConfigurationRequest { - /* - * An identity to be associated with telemetry for data relayed using the - * returned credentials. Must be an existing ACS user identity. If not - * provided, the telemetry will not contain an associated identity value. - */ - @JsonProperty(value = "id") - private String id; - - /* - * Filter the routing methodology returned. If not provided, will return - * all route types in separate ICE servers. - */ - @JsonProperty(value = "routeType") - private RouteType routeType; - - /** - * Get the id property: An identity to be associated with telemetry for data relayed using the returned credentials. - * Must be an existing ACS user identity. If not provided, the telemetry will not contain an associated identity - * value. - * - * @return the id value. - */ - public String getId() { - return this.id; - } - - /** - * Set the id property: An identity to be associated with telemetry for data relayed using the returned credentials. - * Must be an existing ACS user identity. If not provided, the telemetry will not contain an associated identity - * value. - * - * @param id the id value to set. - * @return the CommunicationRelayConfigurationRequest object itself. - */ - public CommunicationRelayConfigurationRequest setId(String id) { - this.id = id; - return this; - } - - /** - * Get the routeType property: Filter the routing methodology returned. If not provided, will return all route types - * in separate ICE servers. - * - * @return the routeType value. - */ - public RouteType getRouteType() { - return this.routeType; - } - - /** - * Set the routeType property: Filter the routing methodology returned. If not provided, will return all route types - * in separate ICE servers. - * - * @param routeType the routeType value to set. - * @return the CommunicationRelayConfigurationRequest object itself. - */ - public CommunicationRelayConfigurationRequest setRouteType(RouteType routeType) { - this.routeType = routeType; - return this; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/package-info.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/package-info.java deleted file mode 100644 index d06843b641f66..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/models/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -/** - * Package containing the data models for CommunicationNetworkTraversalClient. Azure Communication Network Traversal - * Service. - */ -package com.azure.communication.networktraversal.implementation.models; diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/package-info.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/package-info.java deleted file mode 100644 index 31646a4dbe519..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/implementation/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -/** - * Package containing the implementations for CommunicationNetworkTraversalClient. Azure Communication Network Traversal - * Service. - */ -package com.azure.communication.networktraversal.implementation; diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/CommunicationIceServer.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/CommunicationIceServer.java deleted file mode 100644 index aa30b71c3a987..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/CommunicationIceServer.java +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.models; - -import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.List; - -/** An instance of a STUN/TURN server with credentials to be used for ICE negotiation. */ -public final class CommunicationIceServer { - /* - * List of STUN/TURN server URLs. - */ - @JsonProperty(value = "urls", required = true) - private List urls; - - /* - * User account name which uniquely identifies the credentials. - */ - @JsonProperty(value = "username", required = true) - private String username; - - /* - * Credential for the server. - */ - @JsonProperty(value = "credential", required = true) - private String credential; - - /* - * The routing methodology to where the ICE server will be located from the - * client. "any" will have higher reliability while "nearest" will have - * lower latency. It is recommended to default to use the "any" routing - * method unless there are specific scenarios which minimizing latency is - * critical. - */ - @JsonProperty(value = "routeType", required = true) - private RouteType routeType; - - /** - * Default constructor for CommunicationIceServer. - */ - public CommunicationIceServer() { - } - - /** - * Get the urls property: List of STUN/TURN server URLs. - * - * @return the urls value. - */ - public List getUrls() { - return this.urls; - } - - /** - * Set the urls property: List of STUN/TURN server URLs. - * - * @param urls the urls value to set. - * @return the CommunicationIceServer object itself. - */ - CommunicationIceServer setUrls(List urls) { - this.urls = urls; - return this; - } - - /** - * Get the username property: User account name which uniquely identifies the credentials. - * - * @return the username value. - */ - public String getUsername() { - return this.username; - } - - /** - * Set the username property: User account name which uniquely identifies the credentials. - * - * @param username the username value to set. - * @return the CommunicationIceServer object itself. - */ - CommunicationIceServer setUsername(String username) { - this.username = username; - return this; - } - - /** - * Get the credential property: Credential for the server. - * - * @return the credential value. - */ - public String getCredential() { - return this.credential; - } - - /** - * Set the credential property: Credential for the server. - * - * @param credential the credential value to set. - * @return the CommunicationIceServer object itself. - */ - CommunicationIceServer setCredential(String credential) { - this.credential = credential; - return this; - } - - /** - * Get the routeType property: The routing methodology to where the ICE server will be located from the client. - * "any" will have higher reliability while "nearest" will have lower latency. It is recommended to default to use - * the "any" routing method unless there are specific scenarios which minimizing latency is critical. - * - * @return the routeType value. - */ - public RouteType getRouteType() { - return this.routeType; - } - - /** - * Set the routeType property: The routing methodology to where the ICE server will be located from the client. - * "any" will have higher reliability while "nearest" will have lower latency. It is recommended to default to use - * the "any" routing method unless there are specific scenarios which minimizing latency is critical. - * - * @param routeType the routeType value to set. - * @return the CommunicationIceServer object itself. - */ - CommunicationIceServer setRouteType(RouteType routeType) { - this.routeType = routeType; - return this; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/CommunicationRelayConfiguration.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/CommunicationRelayConfiguration.java deleted file mode 100644 index aafd7802fa2f7..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/CommunicationRelayConfiguration.java +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.models; - -import com.fasterxml.jackson.annotation.JsonProperty; -import java.time.OffsetDateTime; -import java.util.List; - -/** A relay configuration containing the STUN/TURN URLs and credentials. */ -public final class CommunicationRelayConfiguration { - /* - * The date for which the username and credentials are not longer valid. - * Will be 48 hours from request time. - */ - @JsonProperty(value = "expiresOn", required = true) - private OffsetDateTime expiresOn; - - /* - * An array representing the credentials and the STUN/TURN server URLs for - * use in ICE negotiations. - */ - @JsonProperty(value = "iceServers", required = true) - private List iceServers; - - /** - * Default constructor for CommunicationRelayConfiguration. - */ - public CommunicationRelayConfiguration() { - } - - /** - * Get the expiresOn property: The date for which the username and credentials are not longer valid. Will be 48 - * hours from request time. - * - * @return the expiresOn value. - */ - public OffsetDateTime getExpiresOn() { - return this.expiresOn; - } - - /** - * Set the expiresOn property: The date for which the username and credentials are not longer valid. Will be 48 - * hours from request time. - * - * @param expiresOn the expiresOn value to set. - * @return the CommunicationRelayConfiguration object itself. - */ - CommunicationRelayConfiguration setExpiresOn(OffsetDateTime expiresOn) { - this.expiresOn = expiresOn; - return this; - } - - /** - * Get the iceServers property: An array representing the credentials and the STUN/TURN server URLs for use in ICE - * negotiations. - * - * @return the iceServers value. - */ - public List getIceServers() { - return this.iceServers; - } - - /** - * Set the iceServers property: An array representing the credentials and the STUN/TURN server URLs for use in ICE - * negotiations. - * - * @param iceServers the iceServers value to set. - * @return the CommunicationRelayConfiguration object itself. - */ - CommunicationRelayConfiguration setIceServers(List iceServers) { - this.iceServers = iceServers; - return this; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/GetRelayConfigurationOptions.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/GetRelayConfigurationOptions.java deleted file mode 100644 index 376606dca75d2..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/GetRelayConfigurationOptions.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.communication.networktraversal.models; - -import com.azure.communication.common.CommunicationUserIdentifier; - -/** - * Additional options for getting a relay configuration. - * - */ -public final class GetRelayConfigurationOptions { - private CommunicationUserIdentifier communicationUser; - private RouteType routeType; - - /** - * Default constructor for GetRelayConfigurationOptions. - */ - public GetRelayConfigurationOptions() { - } - - /** - * Get the communicationUser property: The CommunicationUserIdentifier for whom to issue a token. - * - * @return the communicationUser value. - */ - public CommunicationUserIdentifier getCommunicationUserIdentifier() { - return this.communicationUser; - } - - /** - * Set the communicationUser property: The CommunicationUserIdentifier for whom to issue a token - * - * @param communicationUser the communicationUser value to set. - * @return the GetRelayConfigurationOptions object itself. - */ - public GetRelayConfigurationOptions setCommunicationUserIdentifier(CommunicationUserIdentifier communicationUser) { - this.communicationUser = communicationUser; - return this; - } - - /** - * Get the routeType property: The routing methodology to where the ICE server will be located from the client. - * - * @return the routeType value. - */ - public RouteType getRouteType() { - return this.routeType; - } - - /** - * Set the routeType property: The routing methodology to where the ICE server will be located from the client. - * - * @param routeType the routeType value to set. - * @return the GetRelayConfigurationOptions object itself. - */ - public GetRelayConfigurationOptions setRouteType(RouteType routeType) { - this.routeType = routeType; - return this; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/RouteType.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/RouteType.java deleted file mode 100644 index 56c2ee6d3ac8c..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/RouteType.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package com.azure.communication.networktraversal.models; - -import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; -import java.util.Collection; - -/** Defines values for RouteType. */ -public final class RouteType extends ExpandableStringEnum { - /** - * Default constructor for RouteType. - */ - public RouteType() { - } - - /** Static value any for RouteType. */ - public static final RouteType ANY = fromString("any"); - - /** Static value nearest for RouteType. */ - public static final RouteType NEAREST = fromString("nearest"); - - /** - * Creates or finds a RouteType from its string representation. - * - * @param name a name to look for. - * @return the corresponding RouteType. - */ - @JsonCreator - public static RouteType fromString(String name) { - return fromString(name, RouteType.class); - } - - /** - * Retrieve values collection - * - * @return known RouteType values. - */ - public static Collection values() { - return values(RouteType.class); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/package-info.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/package-info.java deleted file mode 100644 index 999f1a35ee87c..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/models/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -/** - * Package containing classes for CommunicationNetworkTraversalClient. Azure Communication Network Traversal Service. - */ -package com.azure.communication.networktraversal.models; diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/package-info.java b/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/package-info.java deleted file mode 100644 index cab9431d54978..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/com/azure/communication/networktraversal/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** Package containing the classes for AzureCommunicationNetworkTraversal. Azure Communication Networking Service. */ -package com.azure.communication.networktraversal; diff --git a/sdk/communication/azure-communication-networktraversal/src/main/java/module-info.java b/sdk/communication/azure-communication-networktraversal/src/main/java/module-info.java deleted file mode 100644 index 1b246546856c0..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/java/module-info.java +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -module com.azure.communication.networktraversal { - - requires transitive com.azure.communication.common; - - // public API surface area - exports com.azure.communication.networktraversal; - exports com.azure.communication.networktraversal.models; - - opens com.azure.communication.networktraversal.models - to com.fasterxml.jackson.databind; - opens com.azure.communication.networktraversal.implementation.models - to com.fasterxml.jackson.databind, com.azure.core; -} diff --git a/sdk/communication/azure-communication-networktraversal/src/main/resources/azure-communication-networktraversal.properties b/sdk/communication/azure-communication-networktraversal/src/main/resources/azure-communication-networktraversal.properties deleted file mode 100644 index ca812989b4f27..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/main/resources/azure-communication-networktraversal.properties +++ /dev/null @@ -1,2 +0,0 @@ -name=${project.artifactId} -version=${project.version} diff --git a/sdk/communication/azure-communication-networktraversal/src/samples/java/com/azure/communication/networktraversal/CreateAndIssueRelayCredentialsExample.java b/sdk/communication/azure-communication-networktraversal/src/samples/java/com/azure/communication/networktraversal/CreateAndIssueRelayCredentialsExample.java deleted file mode 100644 index 3b6169d0f5534..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/samples/java/com/azure/communication/networktraversal/CreateAndIssueRelayCredentialsExample.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.communication.networktraversal; - -import com.azure.communication.common.CommunicationUserIdentifier; -import com.azure.communication.identity.CommunicationIdentityClient; -import com.azure.communication.identity.CommunicationIdentityClientBuilder; -import com.azure.communication.networktraversal.models.CommunicationRelayConfiguration; -import com.azure.communication.networktraversal.models.CommunicationIceServer; -import com.azure.communication.networktraversal.models.GetRelayConfigurationOptions; -import java.util.List; - -/** - * Shows how to get a CommunicationUserIdentifier using CommunicationIdentityClient - * to later return a relay configuration using CommunicationRelayConfiguration - * - * It iterates over the lis of CommunicationIceServer to print the urls, username and credential - */ -public class CreateAndIssueRelayCredentialsExample { - public static void main(String[] args) { - String connectionString = System.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING"); - CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() - .connectionString(connectionString) - .buildClient(); - - CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder() - .connectionString(connectionString) - .buildClient(); - - CommunicationUserIdentifier user = communicationIdentityClient.createUser(); - System.out.println("User id: " + user.getId()); - - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - - // Define a list of communication token scopes - CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(options); - - System.out.println("Expires on:" + config.getExpiresOn()); - List iceServers = config.getIceServers(); - - for (CommunicationIceServer iceS : iceServers) { - System.out.println("URLS: " + iceS.getUrls()); - System.out.println("Username: " + iceS.getUsername()); - System.out.println("credential: " + iceS.getCredential()); - } - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/samples/java/com/azure/communication/networktraversal/ReadmeSamples.java b/sdk/communication/azure-communication-networktraversal/src/samples/java/com/azure/communication/networktraversal/ReadmeSamples.java deleted file mode 100644 index 6d23b684b28be..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/samples/java/com/azure/communication/networktraversal/ReadmeSamples.java +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.communication.networktraversal; - -import com.azure.communication.common.CommunicationUserIdentifier; -import com.azure.core.credential.AzureKeyCredential; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.communication.identity.CommunicationIdentityClient; -import com.azure.communication.identity.CommunicationIdentityClientBuilder; -import com.azure.communication.networktraversal.models.CommunicationRelayConfiguration; -import com.azure.communication.networktraversal.models.RouteType; -import com.azure.communication.networktraversal.models.CommunicationIceServer; -import com.azure.communication.networktraversal.models.GetRelayConfigurationOptions; -import java.util.List; - -public class ReadmeSamples { - /** - * Sample code for creating a sync Communication Identity Client. - * - * @return the Communication Identity Client. - */ - public CommunicationIdentityClient createCommunicationIdentityClient() { - // You can find your endpoint and access key from your resource in the Azure Portal - String endpoint = "https://.communication.azure.com"; - AzureKeyCredential keyCredential = new AzureKeyCredential(""); - - CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() - .endpoint(endpoint) - .credential(keyCredential) - .buildClient(); - - return communicationIdentityClient; - } - - /** - * Sample code for creating a sync Communication Network Traversal Client. - * - * @return the Communication Relay Client. - */ - public CommunicationRelayClient createCommunicationNetworkTraversalClient() { - // BEGIN: readme-sample-createCommunicationNetworkTraversalClient - // You can find your endpoint and access key from your resource in the Azure Portal - String endpoint = "https://.communication.azure.com"; - AzureKeyCredential keyCredential = new AzureKeyCredential(""); - - CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder() - .endpoint(endpoint) - .credential(keyCredential) - .buildClient(); - // END: readme-sample-createCommunicationNetworkTraversalClient - - return communicationRelayClient; - } - - /** - * Sample code for creating a Relay Client Builder - * - * @return the Communication Relay Client Builder - */ - public CommunicationRelayClientBuilder createCommunicationNetworkTraversalClientBuilder() { - // BEGIN: readme-sample-createCommunicationNetworkTraversalClientBuilder - // You can find your endpoint and access key from your resource in the Azure Portal - String endpoint = "https://.communication.azure.com"; - AzureKeyCredential keyCredential = new AzureKeyCredential(""); - - CommunicationRelayClientBuilder communicationRelayClientBuilder = new CommunicationRelayClientBuilder() - .endpoint(endpoint) - .credential(keyCredential); - // END: readme-sample-createCommunicationNetworkTraversalClientBuilder - - return communicationRelayClientBuilder; - } - - /** - * Sample code for creating a sync Communication Network Traversal Client. - * - * @return the Communication Relay Async Client. - */ - public CommunicationRelayAsyncClient createCommunicationNetworkTraversalAsyncClient() { - // BEGIN: readme-sample-createCommunicationNetworkTraversalAsyncClient - // You can find your endpoint and access key from your resource in the Azure Portal - String endpoint = "https://.communication.azure.com"; - AzureKeyCredential keyCredential = new AzureKeyCredential(""); - - CommunicationRelayAsyncClient communicationRelayClient = new CommunicationRelayClientBuilder() - .endpoint(endpoint) - .credential(keyCredential) - .buildAsyncClient(); - // END: readme-sample-createCommunicationNetworkTraversalAsyncClient - - return communicationRelayClient; - } - - /** - * Sample code for creating a sync Communication Relay Client using connection string. - * - * @return the Communication Relay Client. - */ - public CommunicationRelayClient createCommunicationRelayClientWithConnectionString() { - // BEGIN: readme-sample-createCommunicationRelayClientWithConnectionString - // You can find your connection string from your resource in the Azure Portal - String connectionString = ""; - - CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder() - .connectionString(connectionString) - .buildClient(); - // END: readme-sample-createCommunicationRelayClientWithConnectionString - - return communicationRelayClient; - } - - /** - * Sample code for creating a sync Communication Relay Client using AAD authentication. - * - * @return the Communication Relay Client. - */ - public CommunicationRelayClient createCommunicationRelayClientWithAAD() { - // BEGIN: readme-sample-createCommunicationRelayClientWithAAD - // You can find your endpoint and access key from your resource in the Azure Portal - String endpoint = "https://.communication.azure.com"; - - CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder() - .endpoint(endpoint) - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); - // END: readme-sample-createCommunicationRelayClientWithAAD - - return communicationRelayClient; - } - - /** - * Sample code for getting a relay configuration - * - * @return the created user - */ - public CommunicationRelayConfiguration getRelayConfiguration() { - // BEGIN: readme-sample-getRelayConfiguration - CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); - - CommunicationUserIdentifier user = communicationIdentityClient.createUser(); - System.out.println("User id: " + user.getId()); - - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - - CommunicationRelayClient communicationRelayClient = createCommunicationNetworkTraversalClient(); - CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(options); - - System.out.println("Expires on:" + config.getExpiresOn()); - List iceServers = config.getIceServers(); - - for (CommunicationIceServer iceS : iceServers) { - System.out.println("URLS: " + iceS.getUrls()); - System.out.println("Username: " + iceS.getUsername()); - System.out.println("Credential: " + iceS.getCredential()); - System.out.println("RouteType: " + iceS.getRouteType()); - } - // END: readme-sample-getRelayConfiguration - return config; - } - - /** - * Sample code for getting a relay configuration without identity - * - * @return the created user - */ - public CommunicationRelayConfiguration getRelayConfigurationWithoutIdentity() { - // BEGIN: readme-sample-getRelayConfigurationWithoutIdentity - CommunicationRelayClient communicationRelayClient = createCommunicationNetworkTraversalClient(); - CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(); - - System.out.println("Expires on:" + config.getExpiresOn()); - List iceServers = config.getIceServers(); - - for (CommunicationIceServer iceS : iceServers) { - System.out.println("URLS: " + iceS.getUrls()); - System.out.println("Username: " + iceS.getUsername()); - System.out.println("Credential: " + iceS.getCredential()); - System.out.println("RouteType: " + iceS.getRouteType()); - } - // END: readme-sample-getRelayConfigurationWithoutIdentity - return config; - } - - /** - * Sample code for getting a relay configuration providing RouteType - * - * @return the created user - */ - public CommunicationRelayConfiguration getRelayConfigurationWithRouteType() { - // BEGIN: readme-sample-getRelayConfigurationWithRouteType - - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setRouteType(RouteType.ANY); - - CommunicationRelayClient communicationRelayClient = createCommunicationNetworkTraversalClient(); - CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(options); - - System.out.println("Expires on:" + config.getExpiresOn()); - List iceServers = config.getIceServers(); - - for (CommunicationIceServer iceS : iceServers) { - System.out.println("URLS: " + iceS.getUrls()); - System.out.println("Username: " + iceS.getUsername()); - System.out.println("Credential: " + iceS.getCredential()); - System.out.println("RouteType: " + iceS.getRouteType()); - } - // END: readme-sample-getRelayConfigurationWithRouteType - return config; - } - - /** - * Sample code for troubleshooting - */ - public void createUserTroubleshooting() { - CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); - - // BEGIN: readme-sample-createUserTroubleshooting - try { - CommunicationUserIdentifier user = communicationIdentityClient.createUser(); - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - - CommunicationRelayClient communicationRelayClient = createCommunicationNetworkTraversalClient(); - CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(options); - } catch (RuntimeException ex) { - System.out.println(ex.getMessage()); - } - // END: readme-sample-createUserTroubleshooting - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayAsyncTests.java b/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayAsyncTests.java deleted file mode 100644 index 4519f202e6805..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayAsyncTests.java +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.communication.networktraversal; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import com.azure.communication.common.CommunicationUserIdentifier; -import com.azure.communication.identity.CommunicationIdentityClient; -import com.azure.communication.identity.CommunicationIdentityServiceVersion; -import com.azure.communication.networktraversal.models.CommunicationRelayConfiguration; -import com.azure.communication.networktraversal.models.RouteType; -import com.azure.communication.networktraversal.models.CommunicationIceServer; -import com.azure.communication.networktraversal.models.GetRelayConfigurationOptions; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.Response; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -public class CommunicationRelayAsyncTests extends CommunicationRelayClientTestBase { - private CommunicationRelayAsyncClient asyncClient; - private CommunicationUserIdentifier user; - - private void setupTest(HttpClient httpClient) { - CommunicationIdentityClient communicationIdentityClient = createIdentityClientBuilder(httpClient).serviceVersion(CommunicationIdentityServiceVersion.V2022_10_01).buildClient(); - user = communicationIdentityClient.createUser(); - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientUsingManagedIdentity(HttpClient httpClient) { - // Arrange - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); - asyncClient = setupAsyncClient(builder, "createRelayClientUsingManagedIdentityAsync"); - - // Action & Assert - assertNotNull(asyncClient); - assertNotNull(user.getId()); - - if (user != null) { - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - Mono relayResponse = asyncClient.getRelayConfiguration(options); - - StepVerifier.create(relayResponse) - .assertNext(relayConfig -> { - assertNotNull(relayConfig.getIceServers()); - for (CommunicationIceServer iceS : relayConfig.getIceServers()) { - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - } - }).verifyComplete(); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientWithoutUserIdUsingManagedIdentity(HttpClient httpClient) { - // Arrange - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); - asyncClient = setupAsyncClient(builder, "createRelayClientUsingManagedIdentityAsync"); - - // Action & Assert - assertNotNull(asyncClient); - - if (user != null) { - Mono relayResponse = asyncClient.getRelayConfiguration(); - - StepVerifier.create(relayResponse) - .assertNext(relayConfig -> { - assertNotNull(relayConfig.getIceServers()); - for (CommunicationIceServer iceS : relayConfig.getIceServers()) { - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - } - }).verifyComplete(); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientUsingManagedIdentityWithRouteTypeAny(HttpClient httpClient) { - // Arrange - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); - asyncClient = setupAsyncClient(builder, "createRelayClientUsingManagedIdentityAsync"); - - // Action & Assert - assertNotNull(asyncClient); - assertNotNull(user.getId()); - - if (user != null) { - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - options.setRouteType(RouteType.ANY); - - Mono relayResponse = asyncClient.getRelayConfiguration(options); - - StepVerifier.create(relayResponse) - .assertNext(relayConfig -> { - assertNotNull(relayConfig.getIceServers()); - for (CommunicationIceServer iceS : relayConfig.getIceServers()) { - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - assertEquals(RouteType.ANY, iceS.getRouteType()); - } - }).verifyComplete(); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientUsingConnectionString(HttpClient httpClient) { - // Arrange - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); - asyncClient = setupAsyncClient(builder, "createIdentityClientUsingConnectionStringAsync"); - - // Action & Assert - assertNotNull(asyncClient); - assertNotNull(user.getId()); - if (user != null) { - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - - Mono relayResponse = asyncClient.getRelayConfiguration(options); - - StepVerifier.create(relayResponse) - .assertNext(relayConfig -> { - assertNotNull(relayConfig.getIceServers()); - for (CommunicationIceServer iceS : relayConfig.getIceServers()) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - } - }).verifyComplete(); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientWithoutUserIdUsingConnectionString(HttpClient httpClient) { - // Arrange - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); - asyncClient = setupAsyncClient(builder, "createIdentityClientUsingConnectionStringAsync"); - - // Action & Assert - assertNotNull(asyncClient); - if (user != null) { - Mono relayResponse = asyncClient.getRelayConfiguration(); - - StepVerifier.create(relayResponse) - .assertNext(relayConfig -> { - assertNotNull(relayConfig.getIceServers()); - for (CommunicationIceServer iceS : relayConfig.getIceServers()) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - } - }).verifyComplete(); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void getRelayConfigWithResponseWithRouteTypeNearest(HttpClient httpClient) { - // Arrange - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); - asyncClient = setupAsyncClient(builder, "createRelayClientUsingManagedIdentityAsync"); - - // Action & Assert - assertNotNull(asyncClient); - assertNotNull(user.getId()); - - if (user != null) { - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - options.setRouteType(RouteType.NEAREST); - - Mono> relayConfig = asyncClient.getRelayConfigurationWithResponse(options, null); - - StepVerifier.create(relayConfig) - .assertNext(response -> { - assertEquals(200, response.getStatusCode(), "Expect status code to be 200"); - assertNotNull(response.getValue().getIceServers()); - for (CommunicationIceServer iceS : response.getValue().getIceServers()) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - assertEquals(RouteType.NEAREST, iceS.getRouteType()); - } - }).verifyComplete(); - } - } - - private CommunicationRelayAsyncClient setupAsyncClient(CommunicationRelayClientBuilder builder, String testName) { - return addLoggingPolicy(builder, testName).buildAsyncClient(); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayBuilderTests.java b/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayBuilderTests.java deleted file mode 100644 index 8b191e8e5889d..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayBuilderTests.java +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.communication.networktraversal; - -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 java.net.MalformedURLException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.util.Map; - -import com.azure.communication.networktraversal.implementation.CommunicationRelayResponseMocker; -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.util.ClientOptions; - -import org.junit.jupiter.api.Test; - -import reactor.core.publisher.Mono; - -public class CommunicationRelayBuilderTests { - static final String MOCK_URL = "https://REDACTED.communication.azure.com"; - static final String MOCK_ACCESS_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaGfQSflKxwRJSMeKKF2QT4fwpMeJf36POk6yJVadQssw5c"; - static final String MOCK_CONNECTION_STRING = "endpoint=https://REDACTED.communication.azure.com/;accesskey=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaGfQSflKxwRJSMeKKF2QT4fwpMeJf36POk6yJVadQssw5c"; - - static class NoOpHttpClient implements HttpClient { - @Override - public Mono send(HttpRequest request) { - return Mono.empty(); // NOP - } - } - - private final CommunicationRelayClientBuilder builder = new CommunicationRelayClientBuilder(); - - @Test - public void buildAsyncClientTest() { - builder - .endpoint(MOCK_URL) - .credential(new AzureKeyCredential(MOCK_ACCESS_KEY)) - .httpClient(new NoOpHttpClient() { - @Override - public Mono send(HttpRequest request) { - Map headers = request.getHeaders().toMap(); - assertHMACHeadersExist(headers); - return Mono.just(CommunicationRelayResponseMocker.createUserResult(request)); - } - }); - CommunicationRelayAsyncClient asyncClient = builder.buildAsyncClient(); - assertNotNull(asyncClient); - } - - @Test - public void buildSyncClientTest() { - builder - .endpoint(MOCK_URL) - .credential(new AzureKeyCredential(MOCK_ACCESS_KEY)) - .httpClient(new NoOpHttpClient() { - @Override - public Mono send(HttpRequest request) { - Map headers = request.getHeaders().toMap(); - assertHMACHeadersExist(headers); - return Mono.just(CommunicationRelayResponseMocker.createUserResult(request)); - } - }); - CommunicationRelayClient syncClient = builder.buildClient(); - assertNotNull(syncClient); - } - - @Test - public void buildAsyncClientTestUsingConnectionString() { - builder - .connectionString(MOCK_CONNECTION_STRING) - .httpClient(new NoOpHttpClient() { - @Override - public Mono send(HttpRequest request) { - Map headers = request.getHeaders().toMap(); - - return Mono.just(CommunicationRelayResponseMocker.createUserResult(request)); - } - }); - CommunicationRelayAsyncClient asyncClient = builder.buildAsyncClient(); - assertNotNull(asyncClient); - } - - @Test - public void buildAsyncClientTestUsingConnectionStringAndClientOptions() { - builder - .connectionString(MOCK_CONNECTION_STRING) - .httpClient(new NoOpHttpClient() { - @Override - public Mono send(HttpRequest request) { - Map headers = request.getHeaders().toMap(); - assertHMACHeadersExist(headers); - return Mono.just(CommunicationRelayResponseMocker.createUserResult(request)); - } - }); - CommunicationRelayAsyncClient asyncClient = builder - .clientOptions(new ClientOptions().setApplicationId("testApplicationId")) - .buildAsyncClient(); - assertNotNull(asyncClient); - } - - @Test - public void buildAsyncClientTestUsingConnectionStringAndHttpLogOptions() { - builder - .connectionString(MOCK_CONNECTION_STRING) - .httpClient(new NoOpHttpClient() { - @Override - public Mono send(HttpRequest request) { - Map headers = request.getHeaders().toMap(); - assertHMACHeadersExist(headers); - return Mono.just(CommunicationRelayResponseMocker.createUserResult(request)); - } - }); - CommunicationRelayAsyncClient asyncClient = builder - .httpLogOptions(new HttpLogOptions().setApplicationId("testApplicationId")) - .buildAsyncClient(); - assertNotNull(asyncClient); - } - - @Test - public void createClientWithNoTokenCredentialThrows() - throws NullPointerException, MalformedURLException, InvalidKeyException, NoSuchAlgorithmException { - builder - .endpoint(MOCK_URL) - .httpClient(new NoOpHttpClient()); - assertThrows(Exception.class, () -> { - builder.buildAsyncClient(); - }); - } - - @Test - public void createClientWithNoUrlThrows() - throws NullPointerException, MalformedURLException { - builder - .credential(new AzureKeyCredential(MOCK_ACCESS_KEY)) - .httpClient(new NoOpHttpClient()); - assertThrows(Exception.class, () -> { - builder.buildAsyncClient(); - }); - } - - @Test - public void nullTokenTest() { - assertThrows(NullPointerException.class, () -> { - builder.buildAsyncClient(); - }); - } - - @Test - public void bothRetryOptionsAndRetryPolicySetSync() { - assertThrows(IllegalStateException.class, () -> builder - .endpoint(MOCK_URL) - .credential(new AzureKeyCredential(MOCK_ACCESS_KEY)) - .httpClient(new NoOpHttpClient() { - @Override - public Mono send(HttpRequest request) { - Map headers = request.getHeaders().toMap(); - assertHMACHeadersExist(headers); - return Mono.just(CommunicationRelayResponseMocker.createUserResult(request)); - } - }) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .buildClient()); - } - - @Test - public void bothRetryOptionsAndRetryPolicySetSyncAsync() { - assertThrows(IllegalStateException.class, () -> builder - .endpoint(MOCK_URL) - .credential(new AzureKeyCredential(MOCK_ACCESS_KEY)) - .httpClient(new NoOpHttpClient() { - @Override - public Mono send(HttpRequest request) { - Map headers = request.getHeaders().toMap(); - assertHMACHeadersExist(headers); - return Mono.just(CommunicationRelayResponseMocker.createUserResult(request)); - } - }) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .buildAsyncClient()); - } - - private void assertHMACHeadersExist(Map headers) { - assertTrue(headers.containsKey("Authorization")); - assertTrue(headers.containsKey("x-ms-content-sha256")); - assertNotNull(headers.get("Authorization")); - assertNotNull(headers.get("x-ms-content-sha256")); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayClientTestBase.java b/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayClientTestBase.java deleted file mode 100644 index 880f9c55e321c..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayClientTestBase.java +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.communication.networktraversal; - -import com.azure.communication.common.implementation.CommunicationConnectionString; -import com.azure.communication.identity.CommunicationIdentityClientBuilder; -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpPipelineNextPolicy; -import com.azure.core.http.HttpResponse; -import com.azure.core.test.TestMode; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.models.CustomMatcher; -import com.azure.core.test.models.TestProxySanitizer; -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.UrlBuilder; -import com.azure.identity.DefaultAzureCredentialBuilder; -import reactor.core.publisher.Mono; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.net.MalformedURLException; -import java.net.URL; - -public class CommunicationRelayClientTestBase extends TestProxyTestBase { - protected static final String CONNECTION_STRING = Configuration.getGlobalConfiguration() - .get("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING", "endpoint=https://REDACTED.communication.azure.com/;accesskey=QWNjZXNzS2V5"); - - private static final List JSON_PROPERTIES_TO_REDACT - = new ArrayList<>(Arrays.asList("token", "id", "credential")); - private static List addBodyKeySanitizer() { - return JSON_PROPERTIES_TO_REDACT.stream().map(key -> new TestProxySanitizer(String.format("$..%s", key), null, - "REDACTED", - TestProxySanitizerType.BODY_KEY)).collect(Collectors.toList()); - } - - protected CommunicationRelayClientBuilder createClientBuilder(HttpClient httpClient) { - CommunicationRelayClientBuilder builder = new CommunicationRelayClientBuilder(); - builder.addPolicy((context, next) -> { - try { - URL url = context.getHttpRequest().getUrl(); - URL updatedUrl = UrlBuilder.parse(url).setQueryParameter("api-version", "2022-03-01-preview").toUrl(); - context.getHttpRequest().setUrl(updatedUrl); - return next.process(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - }); - - CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); - String communicationEndpoint = communicationConnectionString.getEndpoint(); - String communicationAccessKey = communicationConnectionString.getAccessKey(); - - builder.endpoint(communicationEndpoint) - .credential(new AzureKeyCredential(communicationAccessKey)) - .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient); - - if (getTestMode() == TestMode.RECORD) { - builder.addPolicy(interceptorManager.getRecordPolicy()); - } - addSanitizersAndMatchers(); - return builder; - } - - protected CommunicationRelayClientBuilder createClientBuilderUsingManagedIdentity(HttpClient httpClient) { - CommunicationRelayClientBuilder builder = new CommunicationRelayClientBuilder(); - builder.addPolicy((context, next) -> { - try { - URL url = context.getHttpRequest().getUrl(); - URL updatedUrl = UrlBuilder.parse(url).setQueryParameter("api-version", "2022-03-01-preview").toUrl(); - context.getHttpRequest().setUrl(updatedUrl); - return next.process(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - }); - - CommunicationConnectionString communicationConnectionString = new CommunicationConnectionString(CONNECTION_STRING); - String communicationEndpoint = communicationConnectionString.getEndpoint(); - - builder - .endpoint(communicationEndpoint) - .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); - - if (getTestMode() == TestMode.PLAYBACK) { - builder.credential(new MockTokenCredential()); - } else { - builder.credential(new DefaultAzureCredentialBuilder().build()); - } - - if (getTestMode() == TestMode.RECORD) { - builder.addPolicy(interceptorManager.getRecordPolicy()); - } - addSanitizersAndMatchers(); - return builder; - } - - protected CommunicationRelayClientBuilder createClientBuilderUsingConnectionString(HttpClient httpClient) { - CommunicationRelayClientBuilder builder = new CommunicationRelayClientBuilder(); - builder.addPolicy((context, next) -> { - try { - URL url = context.getHttpRequest().getUrl(); - URL updatedUrl = UrlBuilder.parse(url).setQueryParameter("api-version", "2022-03-01-preview").toUrl(); - context.getHttpRequest().setUrl(updatedUrl); - return next.process(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - }); - - builder - .connectionString(CONNECTION_STRING) - .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); - - if (getTestMode() == TestMode.RECORD) { - builder.addPolicy(interceptorManager.getRecordPolicy()); - } - addSanitizersAndMatchers(); - return builder; - } - - protected CommunicationIdentityClientBuilder createIdentityClientBuilder(HttpClient httpClient) { - CommunicationIdentityClientBuilder builder = new CommunicationIdentityClientBuilder(); - builder - .connectionString(CONNECTION_STRING) - .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); - - if (getTestMode() == TestMode.RECORD) { - builder.addPolicy(interceptorManager.getRecordPolicy()); - } - addSanitizersAndMatchers(); - return builder; - } - - private void addSanitizersAndMatchers() { - interceptorManager.addMatchers(Arrays.asList(new CustomMatcher().setHeadersKeyOnlyMatch( - Arrays.asList("x-ms-hmac-string-to-sign-base64", "x-ms-content-sha", "x-ms-content-sha256")))); - interceptorManager.addSanitizers(addBodyKeySanitizer()); - } - - protected CommunicationRelayClientBuilder addLoggingPolicy(CommunicationRelayClientBuilder builder, String testName) { - return builder.addPolicy((context, next) -> logHeaders(testName, next)); - } - - private Mono logHeaders(String testName, HttpPipelineNextPolicy next) { - return next.process() - .flatMap(httpResponse -> { - 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")); - return Mono.just(bufferedResponse); - }); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayTests.java b/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayTests.java deleted file mode 100644 index 5f82a2117e937..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/CommunicationRelayTests.java +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.communication.networktraversal; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import com.azure.communication.common.CommunicationUserIdentifier; -import com.azure.communication.identity.CommunicationIdentityClient; -import com.azure.communication.identity.CommunicationIdentityServiceVersion; -import com.azure.communication.networktraversal.models.CommunicationRelayConfiguration; -import com.azure.communication.networktraversal.models.RouteType; -import com.azure.communication.networktraversal.models.CommunicationIceServer; -import com.azure.communication.networktraversal.models.GetRelayConfigurationOptions; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import java.util.List; - -public class CommunicationRelayTests extends CommunicationRelayClientTestBase { - private CommunicationRelayClient client; - private CommunicationUserIdentifier user; - - @Override - protected void afterTest() { - super.afterTest(); - } - - private void setupTest(HttpClient httpClient) { - CommunicationIdentityClient communicationIdentityClient = createIdentityClientBuilder(httpClient) - .serviceVersion(CommunicationIdentityServiceVersion.V2022_10_01) - .buildClient(); - user = communicationIdentityClient.createUser(); - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientUsingManagedIdentity(HttpClient httpClient) { - // Arrange - try { - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); - client = setupClient(builder, "createRelayClientUsingManagedIdentitySync"); - - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - - // Action & Assert - assertNotNull(client); - - CommunicationRelayConfiguration config = client.getRelayConfiguration(options); - List iceServers = config.getIceServers(); - - assertNotNull(config); - assertNotNull(config.getExpiresOn()); - - for (CommunicationIceServer iceS : iceServers) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - assertNotNull(iceS.getRouteType()); - } - } catch (Exception e) { - System.out.println("Exception: " + e); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientWithoutUserIdUsingManagedIdentity(HttpClient httpClient) { - // Arrange - try { - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); - client = setupClient(builder, "createRelayClientUsingManagedIdentitySync"); - - // Action & Assert - assertNotNull(client); - CommunicationRelayConfiguration config = client.getRelayConfiguration(); - List iceServers = config.getIceServers(); - - assertNotNull(config); - assertNotNull(config.getExpiresOn()); - - for (CommunicationIceServer iceS : iceServers) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - } - } catch (Exception e) { - System.out.println("Exception: " + e); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientUsingManagedIdentityWithRouteTypeAny(HttpClient httpClient) { - // Arrange - try { - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); - client = setupClient(builder, "createRelayClientUsingManagedIdentitySync"); - - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - options.setRouteType(RouteType.ANY); - - // Action & Assert - assertNotNull(client); - - CommunicationRelayConfiguration config = client.getRelayConfiguration(options); - List iceServers = config.getIceServers(); - - assertNotNull(config); - assertNotNull(config.getExpiresOn()); - - for (CommunicationIceServer iceS : iceServers) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - assertEquals(RouteType.ANY, iceS.getRouteType()); - } - } catch (Exception e) { - System.out.println("Exception: " + e); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientUsingConnectionString(HttpClient httpClient) { - // Arrange - try { - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); - client = setupClient(builder, "createIdentityClientUsingConnectionStringSync"); - assertNotNull(client); - - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - - CommunicationRelayConfiguration config = client.getRelayConfiguration(options); - - // Action & Assert - List iceServers = config.getIceServers(); - assertNotNull(config); - assertNotNull(config.getExpiresOn()); - - for (CommunicationIceServer iceS : iceServers) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - assertNotNull(iceS.getRouteType()); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientWithoutUserIdUsingConnectionString(HttpClient httpClient) { - // Arrange - try { - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); - client = setupClient(builder, "createIdentityClientUsingConnectionStringSync"); - assertNotNull(client); - CommunicationRelayConfiguration config = client.getRelayConfiguration(); - - // Action & Assert - List iceServers = config.getIceServers(); - assertNotNull(config); - assertNotNull(config.getExpiresOn()); - - for (CommunicationIceServer iceS : iceServers) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void createRelayClientUsingConnectionStringWithRouteTypeNearest(HttpClient httpClient) { - // Arrange - try { - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); - client = setupClient(builder, "createIdentityClientUsingConnectionStringSync"); - - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - options.setRouteType(RouteType.NEAREST); - - CommunicationRelayConfiguration config = client.getRelayConfiguration(options); - - // Action & Assert - assertNotNull(client); - - List iceServers = config.getIceServers(); - assertNotNull(config); - assertNotNull(config.getExpiresOn()); - - for (CommunicationIceServer iceS : iceServers) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - assertEquals(RouteType.NEAREST, iceS.getRouteType()); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @ParameterizedTest - @MethodSource("com.azure.core.test.TestBase#getHttpClients") - public void getRelayConfigWithResponseWithRouteTypeNearest(HttpClient httpClient) { - // Arrange - try { - setupTest(httpClient); - CommunicationRelayClientBuilder builder = createClientBuilder(httpClient); - client = setupClient(builder, "getRelayConfigWithResponse"); - Response response; - - GetRelayConfigurationOptions options = new GetRelayConfigurationOptions(); - options.setCommunicationUserIdentifier(user); - options.setRouteType(RouteType.NEAREST); - - // Action & Assert - response = client.getRelayConfigurationWithResponse(options, Context.NONE); - List iceServers = response.getValue().getIceServers(); - - assertNotNull(response.getValue()); - assertEquals(200, response.getStatusCode(), "Expect status code to be 200"); - assertNotNull(response.getValue().getExpiresOn()); - - for (CommunicationIceServer iceS : iceServers) { - assertNotNull(iceS.getUrls()); - assertNotNull(iceS.getUsername()); - assertNotNull(iceS.getCredential()); - assertEquals(RouteType.NEAREST, iceS.getRouteType()); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private CommunicationRelayClient setupClient(CommunicationRelayClientBuilder builder, String testName) { - return addLoggingPolicy(builder, testName).buildClient(); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/implementation/CommunicationRelayResponseMocker.java b/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/implementation/CommunicationRelayResponseMocker.java deleted file mode 100644 index 21eee6f48b800..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/src/test/java/com/azure/communication/networktraversal/implementation/CommunicationRelayResponseMocker.java +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.communication.networktraversal.implementation; - -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; - -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -public class CommunicationRelayResponseMocker { - - public static HttpResponse createUserResult(HttpRequest request) { - String body = String.format("{\"id\": \"Sanitized\"}"); - return generateMockResponse(body, request, 200); - } - - public static HttpResponse deleteUserResult(HttpRequest request) { - return generateMockResponse("", request, 200); - } - - public static HttpResponse revokeTokenResult(HttpRequest request) { - return generateMockResponse("", request, 200); - } - - public static HttpResponse getTokenResult(HttpRequest request) { - String body = String.format("{\"id\": \"Sanitized\",\n" - + "\"token\": \"Sanitized\",\n" - + "\"expiresOn\": \"2020-08-14T17:37:34.4564877-07:00\"}"); - - return generateMockResponse(body, request, 200); - } - - public static HttpResponse generateMockResponse(String body, HttpRequest request, int statusCode) { - return new HttpResponse(request) { - @Override - public int getStatusCode() { - return statusCode; - } - - @Override - public String getHeaderValue(String name) { - return null; - } - - @Override - public HttpHeaders getHeaders() { - return new HttpHeaders(); - } - - @Override - public Flux getBody() { - return Flux.just(ByteBuffer.wrap(body.getBytes(StandardCharsets.UTF_8))); - } - - @Override - public Mono getBodyAsByteArray() { - return Mono.just(body.getBytes(StandardCharsets.UTF_8)); - } - - @Override - public Mono getBodyAsString() { - return Mono.just(body); - } - - @Override - public Mono getBodyAsString(Charset charset) { - return Mono.just(body); - } - }; - } -} diff --git a/sdk/communication/azure-communication-networktraversal/swagger/README.md b/sdk/communication/azure-communication-networktraversal/swagger/README.md deleted file mode 100644 index bdb481cc0f541..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/swagger/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Azure Communication Network Traversal library for Java - -> see https://aka.ms/autorest -## Getting Started - -To build the SDK for Communication Network Traversal library, simply Install AutoRest and in this folder, run: - -### Setup -```ps -Fork and clone https://github.com/Azure/autorest.java -git checkout main -git submodule update --init --recursive -mvn package -Dlocal -npm install -npm install -g autorest -``` - -### Generation - -```ps -cd -autorest README.md --java --v4 --use=@autorest/java@4.0.2 -``` - -### Code generation settings -``` yaml -tag: package-2022-02-01 -require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/6282e522ef78366170de518e76b8adb0e27563a2/specification/communication/data-plane/NetworkTraversal/readme.md -java: true -output-folder: ..\ -license-header: MICROSOFT_MIT_SMALL -namespace: com.azure.communication.networktraversal -generate-client-as-impl: true -service-interface-as-public: true -custom-types: CommunicationIceServer,CommunicationRelayConfiguration,RouteType -custom-types-subpackage: models -models-subpackage: implementation.models -sync-methods: all -add-context-parameter: true -context-client-method-parameter: true -customization-class: src/main/java/CommunicationRelayCustomization.java -``` diff --git a/sdk/communication/azure-communication-networktraversal/swagger/pom.xml b/sdk/communication/azure-communication-networktraversal/swagger/pom.xml deleted file mode 100644 index 0da32b2900531..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/swagger/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - - - com.azure - azure-code-customization-parent - 1.0.0-beta.1 - ../../../parents/azure-code-customization-parent - - - Microsoft Azure Communication Services Network Traversal client for Java - This package contains client functionality for Microsoft Azure Communication Services Network Traversal - - com.azure.tools - azure-communication-services-network-traversal - 1.0.0-beta.1 - jar - diff --git a/sdk/communication/azure-communication-networktraversal/swagger/src/main/java/CommunicationRelayCustomization.java b/sdk/communication/azure-communication-networktraversal/swagger/src/main/java/CommunicationRelayCustomization.java deleted file mode 100644 index 19374f8bbbf16..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/swagger/src/main/java/CommunicationRelayCustomization.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -import com.azure.autorest.customization.ClassCustomization; -import com.azure.autorest.customization.Customization; -import com.azure.autorest.customization.LibraryCustomization; -import com.azure.autorest.customization.PackageCustomization; -import java.lang.reflect.Modifier; -import org.slf4j.Logger; - -public class CommunicationRelayCustomization extends Customization { - - @Override - public void customize(LibraryCustomization libraryCustomization, Logger logger) { - PackageCustomization models = libraryCustomization.getPackage("com.azure.communication.networktraversal.models"); - String modelToModify = "CommunicationIceServer"; - - models.getClass(modelToModify).getMethod("setUrls").setModifier(0); - models.getClass(modelToModify).getMethod("setUsername").setModifier(0); - models.getClass(modelToModify).getMethod("setRouteType").setModifier(0); - models.getClass(modelToModify).getMethod("setCredential").setModifier(0); - models.getClass(modelToModify).removeAnnotation("Fluent"); - - modelToModify = "CommunicationRelayConfiguration"; - - models.getClass(modelToModify).getMethod("setExpiresOn").setModifier(0); - models.getClass(modelToModify).getMethod("setIceServers").setModifier(0); - models.getClass(modelToModify).removeAnnotation("Fluent"); - } -} diff --git a/sdk/communication/azure-communication-networktraversal/tests.yml b/sdk/communication/azure-communication-networktraversal/tests.yml deleted file mode 100644 index 407ac8b620b13..0000000000000 --- a/sdk/communication/azure-communication-networktraversal/tests.yml +++ /dev/null @@ -1,8 +0,0 @@ -trigger: none - -extends: - template: /sdk/communication/communication-tests-template.yml - parameters: - PackageName: azure-communication-networktraversal - SafeName: azurecommunicationnetworktraversal - Clouds: 'Public' diff --git a/sdk/communication/azure-communication-phonenumbers/pom.xml b/sdk/communication/azure-communication-phonenumbers/pom.xml index f595b0db6c38e..29ef3727cd5af 100644 --- a/sdk/communication/azure-communication-phonenumbers/pom.xml +++ b/sdk/communication/azure-communication-phonenumbers/pom.xml @@ -63,7 +63,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -103,7 +103,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -129,19 +129,19 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -203,7 +203,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 43789327783c4..15d95cadd7c3f 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 b74c96e538055..8d0b33036d340 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/CHANGELOG.md b/sdk/communication/azure-communication-rooms/CHANGELOG.md index 5fe6b5e09332b..1dc38d67f00f7 100644 --- a/sdk/communication/azure-communication-rooms/CHANGELOG.md +++ b/sdk/communication/azure-communication-rooms/CHANGELOG.md @@ -10,6 +10,10 @@ ### Other Changes +#### Dependency Updates + +- Specified `azure-core-http-netty` as version `1.14.2`. + ## 1.1.1 (2024-04-23) diff --git a/sdk/communication/azure-communication-rooms/assets.json b/sdk/communication/azure-communication-rooms/assets.json index d1bfcc8c59d3f..5145793110efd 100644 --- a/sdk/communication/azure-communication-rooms/assets.json +++ b/sdk/communication/azure-communication-rooms/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/communication/azure-communication-rooms", - "Tag": "java/communication/azure-communication-rooms_c1bfd681a1" + "Tag": "java/communication/azure-communication-rooms_5116842cd0" } diff --git a/sdk/communication/azure-communication-rooms/pom.xml b/sdk/communication/azure-communication-rooms/pom.xml index 788d1a506a41c..aaebb8acefae9 100644 --- a/sdk/communication/azure-communication-rooms/pom.xml +++ b/sdk/communication/azure-communication-rooms/pom.xml @@ -59,7 +59,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -75,7 +75,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -105,21 +105,26 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test + + com.azure + azure-core-http-netty + 1.15.0 + @@ -131,7 +136,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 dc472774da6fe..6fe6e520b73d6 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 c78a43f7207b0..d845723cd19b7 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/pom.xml b/sdk/communication/azure-communication-sms/pom.xml index 39d958e5375f5..6239888d59e92 100644 --- a/sdk/communication/azure-communication-sms/pom.xml +++ b/sdk/communication/azure-communication-sms/pom.xml @@ -55,7 +55,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -65,7 +65,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -101,19 +101,19 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -159,7 +159,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 fdffac7a54790..bbfcda8cc29fd 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/communication/azure-resourcemanager-communication/pom.xml b/sdk/communication/azure-resourcemanager-communication/pom.xml index cfacdc3336774..f23890aa15ba7 100644 --- a/sdk/communication/azure-resourcemanager-communication/pom.xml +++ b/sdk/communication/azure-resourcemanager-communication/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/communication/pom.xml b/sdk/communication/pom.xml index 49476b17c49da..b3834304553df 100644 --- a/sdk/communication/pom.xml +++ b/sdk/communication/pom.xml @@ -16,7 +16,6 @@ azure-communication-common azure-communication-email azure-communication-identity - azure-communication-networktraversal azure-communication-phonenumbers azure-communication-sms azure-communication-rooms diff --git a/sdk/confidentialledger/azure-resourcemanager-confidentialledger/pom.xml b/sdk/confidentialledger/azure-resourcemanager-confidentialledger/pom.xml index 9c728ee997e3a..ed292f0f8dd0d 100644 --- a/sdk/confidentialledger/azure-resourcemanager-confidentialledger/pom.xml +++ b/sdk/confidentialledger/azure-resourcemanager-confidentialledger/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/confidentialledger/azure-security-confidentialledger/README.md b/sdk/confidentialledger/azure-security-confidentialledger/README.md index 3e860f7c9dc49..5a41a30d9e043 100644 --- a/sdk/confidentialledger/azure-security-confidentialledger/README.md +++ b/sdk/confidentialledger/azure-security-confidentialledger/README.md @@ -49,7 +49,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.11.4 + 1.12.0 ``` diff --git a/sdk/confidentialledger/azure-security-confidentialledger/pom.xml b/sdk/confidentialledger/azure-security-confidentialledger/pom.xml index 35a1a22c1f870..fbabf480ce884 100644 --- a/sdk/confidentialledger/azure-security-confidentialledger/pom.xml +++ b/sdk/confidentialledger/azure-security-confidentialledger/pom.xml @@ -46,12 +46,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -64,19 +64,19 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 test 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 c91b8d5c6cf1d..d9c220dd946f6 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/confluent/azure-resourcemanager-confluent/pom.xml b/sdk/confluent/azure-resourcemanager-confluent/pom.xml index 77ce69f47f927..305e4aac16b3e 100644 --- a/sdk/confluent/azure-resourcemanager-confluent/pom.xml +++ b/sdk/confluent/azure-resourcemanager-confluent/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/connectedvmware/azure-resourcemanager-connectedvmware/pom.xml b/sdk/connectedvmware/azure-resourcemanager-connectedvmware/pom.xml index 9668138eecd0f..465bfa840c1c3 100644 --- a/sdk/connectedvmware/azure-resourcemanager-connectedvmware/pom.xml +++ b/sdk/connectedvmware/azure-resourcemanager-connectedvmware/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/consumption/azure-resourcemanager-consumption/pom.xml b/sdk/consumption/azure-resourcemanager-consumption/pom.xml index c3d2648eb1e8b..4a3878aaaebd8 100644 --- a/sdk/consumption/azure-resourcemanager-consumption/pom.xml +++ b/sdk/consumption/azure-resourcemanager-consumption/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/containerregistry/azure-containers-containerregistry-perf/pom.xml b/sdk/containerregistry/azure-containers-containerregistry-perf/pom.xml index 63c656c6f0508..16c88d8391dfc 100644 --- a/sdk/containerregistry/azure-containers-containerregistry-perf/pom.xml +++ b/sdk/containerregistry/azure-containers-containerregistry-perf/pom.xml @@ -36,18 +36,18 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 @@ -58,7 +58,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 diff --git a/sdk/containerregistry/azure-containers-containerregistry/pom.xml b/sdk/containerregistry/azure-containers-containerregistry/pom.xml index 4821b8f4cab06..311fc4bc5a522 100644 --- a/sdk/containerregistry/azure-containers-containerregistry/pom.xml +++ b/sdk/containerregistry/azure-containers-containerregistry/pom.xml @@ -46,7 +46,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -56,7 +56,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -105,19 +105,19 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -129,7 +129,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -160,7 +160,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 d844c0558d860..839f886a4b872 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/containerservicefleet/azure-resourcemanager-containerservicefleet/pom.xml b/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/pom.xml index 4c9c3551bf495..790015e76d794 100644 --- a/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/pom.xml +++ b/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/contentsafety/azure-ai-contentsafety/pom.xml b/sdk/contentsafety/azure-ai-contentsafety/pom.xml index 5be92c41dc2ea..e249c7a46e08d 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/pom.xml +++ b/sdk/contentsafety/azure-ai-contentsafety/pom.xml @@ -50,12 +50,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -72,13 +72,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/core/azure-core-amqp/CHANGELOG.md b/sdk/core/azure-core-amqp/CHANGELOG.md index c7a707fe0e08a..90af453d028b6 100644 --- a/sdk/core/azure-core-amqp/CHANGELOG.md +++ b/sdk/core/azure-core-amqp/CHANGELOG.md @@ -4,16 +4,25 @@ ### Features Added -- `WindowedSubscriber` to translate the asynchronous stream of events or messages to `IterableStream` ([38705](https://github.com/Azure/azure-sdk-for-java/pull/38705)). - ### Breaking Changes ### Bugs Fixed ### Other Changes +## 2.9.4 (2024-05-01) + +### Features Added + +- `WindowedSubscriber` to translate the asynchronous stream of events or messages to `IterableStream` ([38705](https://github.com/Azure/azure-sdk-for-java/pull/38705)). + +### Other Changes + +- Improvements to logging. ([#39904](https://github.com/Azure/azure-sdk-for-java/pull/39904)) + #### Dependency Updates +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. - Upgraded `qpid-proton-j-extensions` from `1.2.4` to `1.2.5`. ## 2.9.3 (2024-04-05) diff --git a/sdk/core/azure-core-amqp/README.md b/sdk/core/azure-core-amqp/README.md index 3e3826b174180..3eca2e73753ce 100644 --- a/sdk/core/azure-core-amqp/README.md +++ b/sdk/core/azure-core-amqp/README.md @@ -48,7 +48,7 @@ add the direct dependency to your project as follows. com.azure azure-core-amqp - 2.9.3 + 2.9.4 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-amqp/pom.xml b/sdk/core/azure-core-amqp/pom.xml index 81568ec89a30a..5a9c092cd4992 100644 --- a/sdk/core/azure-core-amqp/pom.xml +++ b/sdk/core/azure-core-amqp/pom.xml @@ -78,7 +78,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.microsoft.azure @@ -139,7 +139,7 @@ com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java index d16abff5d0a83..06823c3127048 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java @@ -145,7 +145,7 @@ private Disposable scheduleRefreshTokenTask(Duration initialRefresh) { (amqpException, interval) -> { final Duration lastRefresh = lastRefreshInterval.get(); - LOGGER.atError() + LOGGER.atWarning() .addKeyValue("scopes", scopes) .addKeyValue(INTERVAL_KEY, interval) .log("Error is transient. Rescheduling authorization task.", amqpException); diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AmqpChannelProcessor.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AmqpChannelProcessor.java index 1d766902842f6..3c1eef933a389 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AmqpChannelProcessor.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AmqpChannelProcessor.java @@ -232,7 +232,7 @@ public void onError(Throwable throwable) { } }); } else { - logger.atWarning() + logger.atError() .addKeyValue(TRY_COUNT_KEY, attemptsMade) .log("Retry attempts exhausted or exception was not retriable.", throwable); @@ -267,8 +267,9 @@ public void subscribe(CoreSubscriber actual) { actual.onSubscribe(Operators.emptySubscription()); actual.onError(lastError); } else { - Operators.error(actual, logger.logExceptionAsError( - new IllegalStateException("Cannot subscribe. Processor is already terminated."))); + IllegalStateException error + = new IllegalStateException("Cannot subscribe. Processor is already terminated."); + Operators.error(actual, logger.logExceptionAsWarning(error)); } return; diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ManagementChannel.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ManagementChannel.java index b6a016be75c81..4a40a9737a2ac 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ManagementChannel.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ManagementChannel.java @@ -138,7 +138,7 @@ private Mono errorIfEmpty(RequestResponseChannel channel, = String.format("entityPath[%s] deliveryState[%s] No response received from management channel.", entityPath, deliveryState); AmqpException exception = new AmqpException(true, error, channel.getErrorContext()); - return logger.atError().addKeyValue(DELIVERY_STATE_KEY, deliveryState).log(exception); + return logger.atWarning().addKeyValue(DELIVERY_STATE_KEY, deliveryState).log(exception); }); } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnection.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnection.java index eff5d3deb4e90..09766e2ddfc4b 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnection.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnection.java @@ -24,7 +24,6 @@ import org.apache.qpid.proton.reactor.Reactor; import reactor.core.Disposable; import reactor.core.Disposables; -import reactor.core.Exceptions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; @@ -176,7 +175,8 @@ public ReactorConnection(String connectionId, ConnectionOptions connectionOption } }).cache(1); - this.subscriptions = Disposables.composite(this.endpointStates.subscribe()); + this.subscriptions = Disposables.composite(this.endpointStates.subscribe(null, + e -> logger.warning("Error occurred while processing connection state.", e))); } /** @@ -222,8 +222,8 @@ public Flux getShutdownSignals() { public Mono getManagementNode(String entityPath) { return Mono.defer(() -> { if (isDisposed()) { - return monoError(logger.atError().addKeyValue(ENTITY_PATH_KEY, entityPath), Exceptions - .propagate(new IllegalStateException("Connection is disposed. Cannot get management instance."))); + return monoError(logger.atWarning().addKeyValue(ENTITY_PATH_KEY, entityPath), + new IllegalStateException("Connection is disposed. Cannot get management instance.")); } final AmqpManagementNode existing = managementNodes.get(entityPath); diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnectionCache.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnectionCache.java index f74831520dcc1..09345d97b5275 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnectionCache.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnectionCache.java @@ -227,7 +227,7 @@ Retry retryWhenSpec(AmqpRetryPolicy retryPolicy) { || (error instanceof RejectedExecutionException)); if (!shouldRetry) { - logger.atWarning() + logger.atError() .addKeyValue(TRY_COUNT_KEY, iteration) .log("Exception is non-retriable, not retrying for a new connection.", error); return Mono.error(error); @@ -246,7 +246,7 @@ Retry retryWhenSpec(AmqpRetryPolicy retryPolicy) { final Duration backoff = retryPolicy.calculateRetryDelay(errorToUse, (int) attempts); if (backoff == null) { - logger.atWarning() + logger.atError() .addKeyValue(TRY_COUNT_KEY, iteration) .log("Retry is disabled, not retrying for a new connection.", error); return Mono.error(error); diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorReceiver.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorReceiver.java index 08cd26208f0fc..5fdf1ce8d5b30 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorReceiver.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorReceiver.java @@ -228,7 +228,8 @@ public Mono updateDisposition(String deliveryTag, DeliveryState deliverySt @Override public Mono addCredits(int credits) { if (isDisposed()) { - return monoError(logger, new IllegalStateException("Cannot add credits to closed link: " + getLinkName())); + return monoError(logger.atWarning(), + new IllegalStateException("Cannot add credits to closed link: " + getLinkName())); } return Mono.create(sink -> { diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorSender.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorSender.java index c9763e44d8dcb..7b4490a9ad75e 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorSender.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorSender.java @@ -14,7 +14,6 @@ import com.azure.core.amqp.implementation.handler.SendLinkHandler; import com.azure.core.util.AsyncCloseable; import com.azure.core.util.CoreUtils; -import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import org.apache.qpid.proton.Proton; import org.apache.qpid.proton.amqp.Binary; @@ -70,6 +69,7 @@ import static com.azure.core.amqp.implementation.ClientConstants.MAX_AMQP_HEADER_SIZE_BYTES; import static com.azure.core.amqp.implementation.ClientConstants.NOT_APPLICABLE; import static com.azure.core.amqp.implementation.ClientConstants.SERVER_BUSY_BASE_SLEEP_TIME_IN_SECS; +import static com.azure.core.util.FluxUtil.monoError; import static java.nio.charset.StandardCharsets.UTF_8; /** @@ -153,7 +153,7 @@ class ReactorSender implements AmqpSendLink, AsyncCloseable, AutoCloseable { handler.getConnectionId(), handler.getLinkName()); this.endpointStates = this.handler.getEndpointStates().map(state -> { - logger.verbose("State {}", state); + logger.atVerbose().addKeyValue("state", state).log("onEndpointState"); this.hasConnected.set(state == EndpointState.ACTIVE); return AmqpEndpointStateUtil.getConnectionState(state); }).doOnError(error -> { @@ -332,7 +332,7 @@ private byte[] batchBinaryDataSectionBytes(Message sectionMessage, int maxMessag } private Mono batchBufferOverflowError(int maxMessageSize) { - return FluxUtil.monoError(logger, + return monoError(logger, new AmqpException( false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, String.format(Locale.US, "Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024), diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorSession.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorSession.java index 97b4977212727..86317730c41dd 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorSession.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorSession.java @@ -33,7 +33,6 @@ import org.apache.qpid.proton.engine.Session; import reactor.core.Disposable; import reactor.core.Disposables; -import reactor.core.Exceptions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoSink; @@ -61,6 +60,7 @@ import static com.azure.core.amqp.implementation.ClientConstants.LINK_NAME_KEY; import static com.azure.core.amqp.implementation.ClientConstants.NOT_APPLICABLE; import static com.azure.core.amqp.implementation.ClientConstants.SESSION_NAME_KEY; +import static com.azure.core.util.FluxUtil.monoError; /** * Represents an AMQP session using proton-j reactor. @@ -297,11 +297,9 @@ Mono closeAsync(String message, ErrorCondition errorCondition, boolean dis @Override public Mono getOrCreateTransactionCoordinator() { if (isDisposed()) { - return Mono.error(logger.atError() - .addKeyValue(SESSION_NAME_KEY, sessionName) - .log(new AmqpException(true, String - .format("Cannot create coordinator send link %s from a closed session.", TRANSACTION_LINK_NAME), - sessionHandler.getErrorContext()))); + return monoError(logger.atWarning().addKeyValue(SESSION_NAME_KEY, sessionName), new AmqpException(true, + String.format("Cannot create coordinator send link %s from a closed session.", TRANSACTION_LINK_NAME), + sessionHandler.getErrorContext())); } final TransactionCoordinator existing = transactionCoordinator.get(); @@ -354,16 +352,13 @@ protected Mono createConsumer(String linkName, String entityPat ConsumerFactory consumerFactory) { if (isDisposed()) { - LoggingEventBuilder logBuilder = logger.atError() + LoggingEventBuilder logBuilder = logger.atWarning() .addKeyValue(SESSION_NAME_KEY, sessionName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(LINK_NAME_KEY, linkName); - // TODO(limolkova) this can be simplified with FluxUtil.monoError(LoggingEventBuilder), not using it for now - // to allow using azure-core-amqp with stable azure-core 1.24.0 to simplify dependency management - // we should switch to it once monoError(LoggingEventBuilder) ships in stable azure-core - return Mono.error(logBuilder.log(Exceptions.propagate(new AmqpException(true, - "Cannot create receive link from a closed session.", sessionHandler.getErrorContext())))); + return monoError(logBuilder, new AmqpException(true, "Cannot create receive link from a closed session.", + sessionHandler.getErrorContext())); } final LinkSubscription existingLink = openReceiveLinks.get(linkName); @@ -447,16 +442,13 @@ private Mono createProducer(String linkName, String entityPath, Map linkProperties, boolean requiresAuthorization) { if (isDisposed()) { - LoggingEventBuilder logBuilder = logger.atError() + LoggingEventBuilder logBuilder = logger.atWarning() .addKeyValue(SESSION_NAME_KEY, sessionName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(LINK_NAME_KEY, linkName); - // TODO(limolkova) this can be simplified with FluxUtil.monoError(LoggingEventBuilder), not using it for now - // to allow using azure-core-amqp with stable azure-core 1.24.0 to simplify dependency management - // we should switch to it once monoError(LoggingEventBuilder) ships in stable azure-core - return Mono.error(logBuilder.log(Exceptions.propagate(new AmqpException(true, - "Cannot create send link from a closed session.", sessionHandler.getErrorContext())))); + return monoError(logBuilder, new AmqpException(true, "Cannot create send link from a closed session.", + sessionHandler.getErrorContext())); } final LinkSubscription existing = openSendLinks.get(linkName); diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ConnectionHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ConnectionHandler.java index 542c925c80d5d..4db6799122b34 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ConnectionHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ConnectionHandler.java @@ -53,22 +53,6 @@ public class ConnectionHandler extends Handler { private final SslPeerDetails peerDetails; private final AmqpMetricsProvider metricProvider; - /** - * Creates a handler that handles proton-j's connection events. - * - * @param connectionId Identifier for this connection. - * @param connectionOptions Options used when creating the AMQP connection. - * @param peerDetails The peer details for this connection. - * @deprecated use {@link ConnectionHandler#ConnectionHandler(String, ConnectionOptions, SslPeerDetails, AmqpMetricsProvider)} instead. - * @throws NullPointerException if {@code connectionOptions} or {@code peerDetails} is null. - */ - @Deprecated - public ConnectionHandler(final String connectionId, final ConnectionOptions connectionOptions, - SslPeerDetails peerDetails) { - this(connectionId, connectionOptions, peerDetails, - new AmqpMetricsProvider(null, connectionOptions.getFullyQualifiedNamespace(), null)); - } - /** * Creates a handler that handles proton-j's connection events. * diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ReceiveLinkHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ReceiveLinkHandler.java index f5a6852b8e8a8..89f31f7baa673 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ReceiveLinkHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ReceiveLinkHandler.java @@ -50,20 +50,6 @@ public class ReceiveLinkHandler extends LinkHandler { private final Set queuedDeliveries = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final String entityPath; - /** - * Creates a new instance of ReceiveLinkHandler. - * - * @param connectionId Identifier for the connection. - * @param hostname Hostname of the connection. - * @param linkName Name of the link. - * @param entityPath Address to the entity. - * @deprecated use {@link #ReceiveLinkHandler(String, String, String, String, AmqpMetricsProvider)} instead. - */ - @Deprecated - public ReceiveLinkHandler(String connectionId, String hostname, String linkName, String entityPath) { - this(connectionId, hostname, linkName, entityPath, new AmqpMetricsProvider(null, hostname, entityPath)); - } - /** * Creates a new instance of ReceiveLinkHandler. * diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ReceiverUnsettledDeliveries.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ReceiverUnsettledDeliveries.java index df9c0cc4a0fc3..d25ab68c7d6d2 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ReceiverUnsettledDeliveries.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ReceiverUnsettledDeliveries.java @@ -181,7 +181,7 @@ public boolean containsDelivery(UUID deliveryTag) { */ public Mono sendDisposition(String deliveryTag, DeliveryState desiredState) { if (isTerminated.get()) { - return monoError(logger, DeliveryNotOnLinkException.linkClosed(deliveryTag, desiredState)); + return monoError(logger.atWarning(), DeliveryNotOnLinkException.linkClosed(deliveryTag, desiredState)); } else { return sendDispositionImpl(deliveryTag, desiredState); } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/SendLinkHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/SendLinkHandler.java index 052dc661802d2..18c10544fae8d 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/SendLinkHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/SendLinkHandler.java @@ -46,21 +46,6 @@ public class SendLinkHandler extends LinkHandler { private final Sinks.Many creditProcessor = Sinks.many().unicast().onBackpressureBuffer(); private final Sinks.Many deliveryProcessor = Sinks.many().multicast().onBackpressureBuffer(); - /** - * Creates a new instance of SendLinkHandler. - * - * @param connectionId The identifier of the connection this link belongs to. - * @param hostname The hostname for the connection. - * @param linkName The name of the link. - * @param entityPath The entity path this link is connected to. - * @deprecated use {@link SendLinkHandler#SendLinkHandler(String, String, String, String, AmqpMetricsProvider)} - * instead. - */ - @Deprecated - public SendLinkHandler(String connectionId, String hostname, String linkName, String entityPath) { - this(connectionId, hostname, linkName, entityPath, new AmqpMetricsProvider(null, hostname, null)); - } - /** * Creates a new instance of SendLinkHandler. * diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/SessionHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/SessionHandler.java index c04dacd3dc3aa..eee9eaee0feda 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/SessionHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/SessionHandler.java @@ -32,24 +32,6 @@ public class SessionHandler extends Handler { private final ReactorDispatcher reactorDispatcher; private final AmqpMetricsProvider metricsProvider; - /** - * Creates a session handler. - * - * @param connectionId Identifier for the connection. - * @param hostname Hostname of the connection. - * @param sessionName Name of the session. - * @param reactorDispatcher Reactor dispatcher. - * @param openTimeout Timeout for opening the session. - * @deprecated use {@link #SessionHandler(String, String, String, ReactorDispatcher, Duration, AmqpMetricsProvider)} - * instead. - */ - @Deprecated - public SessionHandler(String connectionId, String hostname, String sessionName, ReactorDispatcher reactorDispatcher, - Duration openTimeout) { - this(connectionId, hostname, sessionName, reactorDispatcher, openTimeout, - new AmqpMetricsProvider(null, hostname, null)); - } - /** * Creates a session handler. * diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandler.java index 89f8bbd379cfc..0f60e64f3c8c7 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandler.java @@ -190,8 +190,10 @@ public void onTransportError(Event event) { final URI url = createURI(fullyQualifiedNamespace, port); final InetSocketAddress address = new InetSocketAddress(hostNameParts[0], port); - logger.atError() - .log("Failed to connect to url: '{}', proxy host: '{}'", url, address.getHostString(), ioException); + logger.atWarning() + .addKeyValue("url", url) + .addKeyValue("proxyHost", address.getHostString()) + .log("Failed to connect.", ioException); final ProxySelector proxySelector = ProxySelector.getDefault(); if (proxySelector != null) { diff --git a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorHandlerProviderTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorHandlerProviderTest.java index 198f89602797b..1fcf1bd9437b4 100644 --- a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorHandlerProviderTest.java +++ b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorHandlerProviderTest.java @@ -131,7 +131,7 @@ public void teardown() throws Exception { @SuppressWarnings("deprecation") public void constructorNull() { // Act - assertThrows(NullPointerException.class, () -> new ReactorHandlerProvider(null)); + assertThrows(NullPointerException.class, () -> new ReactorHandlerProvider(null, null)); } @Test diff --git a/sdk/core/azure-core-experimental/CHANGELOG.md b/sdk/core/azure-core-experimental/CHANGELOG.md index fa653bcd45108..10f571930bb79 100644 --- a/sdk/core/azure-core-experimental/CHANGELOG.md +++ b/sdk/core/azure-core-experimental/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.50 (Unreleased) +## 1.0.0-beta.51 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 1.0.0-beta.50 (2024-05-01) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + ## 1.0.0-beta.49 (2024-04-05) ### Breaking Changes diff --git a/sdk/core/azure-core-experimental/README.md b/sdk/core/azure-core-experimental/README.md index 1284eeb0cda5f..565e9c4702f02 100644 --- a/sdk/core/azure-core-experimental/README.md +++ b/sdk/core/azure-core-experimental/README.md @@ -17,7 +17,7 @@ Azure Core Experimental contains types that are being evaluated and might eventu com.azure azure-core-experimental - 1.0.0-beta.49 + 1.0.0-beta.50 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-experimental/pom.xml b/sdk/core/azure-core-experimental/pom.xml index d4c7023fbfff0..aaacbfc94d448 100644 --- a/sdk/core/azure-core-experimental/pom.xml +++ b/sdk/core/azure-core-experimental/pom.xml @@ -15,7 +15,7 @@ com.azure azure-core-experimental jar - 1.0.0-beta.50 + 1.0.0-beta.51 Microsoft Azure Java Core Experimental Library This package contains experimental core types for Azure Java clients. @@ -80,7 +80,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 diff --git a/sdk/core/azure-core-http-jdk-httpclient/CHANGELOG.md b/sdk/core/azure-core-http-jdk-httpclient/CHANGELOG.md index 6279829fdd037..3c59c64f53dfc 100644 --- a/sdk/core/azure-core-http-jdk-httpclient/CHANGELOG.md +++ b/sdk/core/azure-core-http-jdk-httpclient/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.13 (Unreleased) +## 1.0.0-beta.14 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 1.0.0-beta.13 (2024-05-01) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + ## 1.0.0-beta.12 (2024-04-05) ### Features Added diff --git a/sdk/core/azure-core-http-jdk-httpclient/README.md b/sdk/core/azure-core-http-jdk-httpclient/README.md index b3181a427a837..a197e383467f3 100644 --- a/sdk/core/azure-core-http-jdk-httpclient/README.md +++ b/sdk/core/azure-core-http-jdk-httpclient/README.md @@ -16,7 +16,7 @@ part of JDK 11. com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-http-jdk-httpclient/pom.xml b/sdk/core/azure-core-http-jdk-httpclient/pom.xml index f54476e757495..40282939dfda0 100644 --- a/sdk/core/azure-core-http-jdk-httpclient/pom.xml +++ b/sdk/core/azure-core-http-jdk-httpclient/pom.xml @@ -15,7 +15,7 @@ com.azure azure-core-http-jdk-httpclient jar - 1.0.0-beta.13 + 1.0.0-beta.14 Microsoft Azure JDK HTTP Client Library This package contains the Azure HTTP client library using the JDK HttpClient API. @@ -78,27 +78,27 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 test-jar test com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test-jar test diff --git a/sdk/core/azure-core-http-netty/CHANGELOG.md b/sdk/core/azure-core-http-netty/CHANGELOG.md index a1fd00510cae9..c62424c821300 100644 --- a/sdk/core/azure-core-http-netty/CHANGELOG.md +++ b/sdk/core/azure-core-http-netty/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.15.0-beta.1 (Unreleased) +## 1.16.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,21 @@ ### Other Changes +## 1.15.0 (2024-05-01) + +### Bugs Fixed + +- Fixed a bug where mismatch Netty versions were always being reported, even if they were correct. ([#39591](https://github.com/Azure/azure-sdk-for-java/pull/39591)) + +### Other Changes + +- If a Reactor Netty `HttpClient` is passed and has a `LoggingHandler` configured the + `NettyAsyncHttpClientBuilder.wiretap` value is ignored, the builder method is now deprecated as well. ([#39976](https://github.com/Azure/azure-sdk-for-java/pull/39976)) + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + ## 1.14.2 (2024-04-05) ### Other Changes diff --git a/sdk/core/azure-core-http-netty/README.md b/sdk/core/azure-core-http-netty/README.md index dc4067b1b7c7f..01a9413629e93 100644 --- a/sdk/core/azure-core-http-netty/README.md +++ b/sdk/core/azure-core-http-netty/README.md @@ -47,7 +47,7 @@ add the direct dependency to your project as follows. com.azure azure-core-http-netty - 1.14.2 + 1.15.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-http-netty/pom.xml b/sdk/core/azure-core-http-netty/pom.xml index d3b37fe127e1a..fae57fc5b8bd3 100644 --- a/sdk/core/azure-core-http-netty/pom.xml +++ b/sdk/core/azure-core-http-netty/pom.xml @@ -15,7 +15,7 @@ com.azure azure-core-http-netty jar - 1.15.0-beta.1 + 1.16.0-beta.1 Microsoft Azure Netty HTTP Client Library This package contains the Netty HTTP client plugin for azure-core. @@ -83,7 +83,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 @@ -157,20 +157,20 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 test-jar test com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test-jar test diff --git a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClient.java b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClient.java index 2ee6106d12223..944b72081b40e 100644 --- a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClient.java +++ b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClient.java @@ -78,7 +78,6 @@ *

  * HttpClient client = new NettyAsyncHttpClientBuilder()
  *     .port(8080)
- *     .wiretap(true)
  *     .build();
  * 
* diff --git a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilder.java b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilder.java index 00eeb44fa0403..75083d268df59 100644 --- a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilder.java +++ b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilder.java @@ -18,6 +18,7 @@ import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.handler.logging.LoggingHandler; import io.netty.resolver.AddressResolverGroup; import io.netty.resolver.DefaultAddressResolverGroup; import io.netty.resolver.NoopAddressResolverGroup; @@ -61,7 +62,6 @@ *
  * HttpClient client = new NettyAsyncHttpClientBuilder()
  *     .port(8080)
- *     .wiretap(true)
  *     .build();
  * 
* @@ -79,7 +79,6 @@ *
  * HttpClient client = new NettyAsyncHttpClientBuilder()
  *     .port(8080)
- *     .wiretap(true)
  *     .build();
  * 
* @@ -92,7 +91,6 @@ *
  * HttpClient client = new NettyAsyncHttpClientBuilder()
  *     .port(8080)
- *     .wiretap(true)
  *     .build();
  * 
* @@ -216,7 +214,6 @@ public com.azure.core.http.HttpClient build() { // instead of overwritten. HttpResponseDecoderSpec initialSpec = nettyHttpClient.configuration().decoder(); nettyHttpClient = nettyHttpClient.port(port) - .wiretap(enableWiretap) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) getTimeoutMillis(connectTimeout, DEFAULT_CONNECT_TIMEOUT)) // TODO (alzimmer): What does validating HTTP response headers get us? @@ -225,6 +222,15 @@ public com.azure.core.http.HttpClient build() { (request, connection) -> addHandler(request, connection, writeTimeout, responseTimeout, readTimeout)) .doAfterResponseSuccess((ignored, connection) -> removeHandler(connection)); + LoggingHandler loggingHandler = nettyHttpClient.configuration().loggingHandler(); + if (loggingHandler == null) { + // Only enable wiretap if the LoggingHandler is null. If the LoggingHandler isn't null this means that a + // base client was passed with logging enabled. 'wiretap(boolean)' is a basic API that doesn't allow for + // in-depth settings to be done on how logging works, so setting it always can replace a customized logger + // with a basic one that isn't as useful in troubleshooting scenarios. + nettyHttpClient.wiretap(enableWiretap); + } + Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; @@ -349,7 +355,11 @@ public NettyAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { * * @param enableWiretap Flag indicating wiretap status * @return the updated NettyAsyncHttpClientBuilder object. + * @deprecated If logging should be enabled as the Reactor Netty level, construct the builder using + * {@link #NettyAsyncHttpClientBuilder(HttpClient)} where the passed Reactor Netty HttpClient has logging + * configured. */ + @Deprecated public NettyAsyncHttpClientBuilder wiretap(boolean enableWiretap) { this.enableWiretap = enableWiretap; return this; diff --git a/sdk/core/azure-core-http-netty/src/samples/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilderJavaDocCodeSnippets.java b/sdk/core/azure-core-http-netty/src/samples/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilderJavaDocCodeSnippets.java index 64031ecb7f81b..348e8b1b20f89 100644 --- a/sdk/core/azure-core-http-netty/src/samples/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilderJavaDocCodeSnippets.java +++ b/sdk/core/azure-core-http-netty/src/samples/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilderJavaDocCodeSnippets.java @@ -28,7 +28,6 @@ public void simpleInstantiation() { // BEGIN: com.azure.core.http.netty.instantiation-simple HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) - .wiretap(true) .build(); // END: com.azure.core.http.netty.instantiation-simple } diff --git a/sdk/core/azure-core-http-netty/src/test/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilderTests.java b/sdk/core/azure-core-http-netty/src/test/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilderTests.java index f679691ae15ce..85abd25bf71e5 100644 --- a/sdk/core/azure-core-http-netty/src/test/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilderTests.java +++ b/sdk/core/azure-core-http-netty/src/test/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilderTests.java @@ -488,6 +488,7 @@ public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, Sock /** * Tests when {@code wiretap} is set to {@code true} the Netty pipeline will have a {@link LoggingHandler} added. */ + @SuppressWarnings("deprecation") @Test public void buildWiretappedClient() { HttpClient validatorClient = HttpClient.create() diff --git a/sdk/core/azure-core-http-okhttp/CHANGELOG.md b/sdk/core/azure-core-http-okhttp/CHANGELOG.md index d322dccc56dad..f9b70ce977ed8 100644 --- a/sdk/core/azure-core-http-okhttp/CHANGELOG.md +++ b/sdk/core/azure-core-http-okhttp/CHANGELOG.md @@ -10,6 +10,14 @@ ### Other Changes +## 1.11.21 (2024-05-01) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + ## 1.11.20 (2024-04-05) ### Other Changes diff --git a/sdk/core/azure-core-http-okhttp/README.md b/sdk/core/azure-core-http-okhttp/README.md index 2cb849c721903..f11a5890a9023 100644 --- a/sdk/core/azure-core-http-okhttp/README.md +++ b/sdk/core/azure-core-http-okhttp/README.md @@ -47,7 +47,7 @@ add the direct dependency to your project as follows. com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-http-okhttp/pom.xml b/sdk/core/azure-core-http-okhttp/pom.xml index 00ccfa4a88493..70640ecd77cbd 100644 --- a/sdk/core/azure-core-http-okhttp/pom.xml +++ b/sdk/core/azure-core-http-okhttp/pom.xml @@ -79,7 +79,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 @@ -98,20 +98,20 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 test-jar test com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test-jar test diff --git a/sdk/core/azure-core-http-vertx/CHANGELOG.md b/sdk/core/azure-core-http-vertx/CHANGELOG.md index f6c4d9eabdbd3..8c692e2a2dff7 100644 --- a/sdk/core/azure-core-http-vertx/CHANGELOG.md +++ b/sdk/core/azure-core-http-vertx/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.18 (Unreleased) +## 1.0.0-beta.19 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 1.0.0-beta.18 (2024-05-01) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + ## 1.0.0-beta.17 (2024-04-05) ### Bugs Fixed diff --git a/sdk/core/azure-core-http-vertx/README.md b/sdk/core/azure-core-http-vertx/README.md index 93d782b77d257..c5f452b629f03 100644 --- a/sdk/core/azure-core-http-vertx/README.md +++ b/sdk/core/azure-core-http-vertx/README.md @@ -16,7 +16,7 @@ Azure Core Vert.x HTTP client is a plugin for the `azure-core` HTTP client API. com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 ``` diff --git a/sdk/core/azure-core-http-vertx/pom.xml b/sdk/core/azure-core-http-vertx/pom.xml index 60a12e71f36a4..b077001bce306 100644 --- a/sdk/core/azure-core-http-vertx/pom.xml +++ b/sdk/core/azure-core-http-vertx/pom.xml @@ -15,7 +15,7 @@ com.azure azure-core-http-vertx jar - 1.0.0-beta.18 + 1.0.0-beta.19 Microsoft Azure Vert.x HTTP Client Library This package contains the Vert.x HTTP client plugin for azure-core. @@ -79,7 +79,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 @@ -106,20 +106,20 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 test-jar test com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test-jar test diff --git a/sdk/core/azure-core-management/CHANGELOG.md b/sdk/core/azure-core-management/CHANGELOG.md index 67be631bbb0ae..925820f389119 100644 --- a/sdk/core/azure-core-management/CHANGELOG.md +++ b/sdk/core/azure-core-management/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.14.0-beta.1 (Unreleased) +## 1.15.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,18 @@ ### Other Changes +## 1.14.0 (2024-05-01) + +### Features Added + +- Added `managedHsmDnsSuffix` getter and `storageEndpointSuffix` to `AzureEnvironment`. ([#39647](https://github.com/Azure/azure-sdk-for-java/pull/39647)) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + ## 1.13.0 (2024-04-05) ### Features Added diff --git a/sdk/core/azure-core-management/README.md b/sdk/core/azure-core-management/README.md index 64eb8dac278e3..27fca41de46f8 100644 --- a/sdk/core/azure-core-management/README.md +++ b/sdk/core/azure-core-management/README.md @@ -15,7 +15,7 @@ Azure Core Management library is a collection of classes common to the [Azure Re com.azure azure-core-management - 1.13.0 + 1.14.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-management/pom.xml b/sdk/core/azure-core-management/pom.xml index c0b347260e10e..e961b7f3ab1a1 100644 --- a/sdk/core/azure-core-management/pom.xml +++ b/sdk/core/azure-core-management/pom.xml @@ -13,7 +13,7 @@ com.azure azure-core-management - 1.14.0-beta.1 + 1.15.0-beta.1 jar Microsoft Azure Management Java Core Library @@ -77,7 +77,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 @@ -107,7 +107,7 @@ com.azure azure-core-http-netty - 1.15.0-beta.1 + 1.16.0-beta.1 test 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 d20086bf9d0c4..031ed96e6cd0e 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-metrics-opentelemetry/CHANGELOG.md b/sdk/core/azure-core-metrics-opentelemetry/CHANGELOG.md index 8b48e8f386478..54e8588013c27 100644 --- a/sdk/core/azure-core-metrics-opentelemetry/CHANGELOG.md +++ b/sdk/core/azure-core-metrics-opentelemetry/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.19 (Unreleased) +## 1.0.0-beta.20 (Unreleased) ### Features Added @@ -10,6 +10,15 @@ ### Other Changes +## 1.0.0-beta.19 (2024-05-01) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. +- Upgraded `opentelemetry-api` from `1.36.0` to `1.37.0`. + ## 1.0.0-beta.18 (2024-04-05) ### Other Changes diff --git a/sdk/core/azure-core-metrics-opentelemetry/pom.xml b/sdk/core/azure-core-metrics-opentelemetry/pom.xml index 05d3ec3cf59cc..c0af751b63aad 100644 --- a/sdk/core/azure-core-metrics-opentelemetry/pom.xml +++ b/sdk/core/azure-core-metrics-opentelemetry/pom.xml @@ -12,7 +12,7 @@ com.azure azure-core-metrics-opentelemetry - 1.0.0-beta.19 + 1.0.0-beta.20 Microsoft Azure OpenTelemetry metrics plugin This package contains the OpenTelemetry metrics plugin for Azure client libraries. @@ -54,7 +54,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.google.code.findbugs @@ -81,13 +81,13 @@ com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test com.azure azure-core-http-netty - 1.15.0-beta.1 + 1.16.0-beta.1 test diff --git a/sdk/core/azure-core-perf/pom.xml b/sdk/core/azure-core-perf/pom.xml index ab18409ffe963..977c2d10af638 100644 --- a/sdk/core/azure-core-perf/pom.xml +++ b/sdk/core/azure-core-perf/pom.xml @@ -25,12 +25,12 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.azure azure-core-http-netty - 1.15.0-beta.1 + 1.16.0-beta.1 com.azure diff --git a/sdk/core/azure-core-serializer-avro-apache/CHANGELOG.md b/sdk/core/azure-core-serializer-avro-apache/CHANGELOG.md index 06e79328bb435..4215af3441aeb 100644 --- a/sdk/core/azure-core-serializer-avro-apache/CHANGELOG.md +++ b/sdk/core/azure-core-serializer-avro-apache/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.46 (Unreleased) +## 1.0.0-beta.47 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 1.0.0-beta.46 (2024-05-01) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + ## 1.0.0-beta.45 (2024-04-05) ### Other Changes diff --git a/sdk/core/azure-core-serializer-avro-apache/README.md b/sdk/core/azure-core-serializer-avro-apache/README.md index a82a9b4c98c3f..086fc49144922 100644 --- a/sdk/core/azure-core-serializer-avro-apache/README.md +++ b/sdk/core/azure-core-serializer-avro-apache/README.md @@ -15,7 +15,7 @@ Azure Core Apache Avro Serializer is a plugin for the `azure-core` `AvroSerializ com.azure azure-core-serializer-avro-apache - 1.0.0-beta.45 + 1.0.0-beta.46 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-serializer-avro-apache/pom.xml b/sdk/core/azure-core-serializer-avro-apache/pom.xml index 62c3d0e689d29..7845d3f184e1d 100644 --- a/sdk/core/azure-core-serializer-avro-apache/pom.xml +++ b/sdk/core/azure-core-serializer-avro-apache/pom.xml @@ -15,7 +15,7 @@ com.azure azure-core-serializer-avro-apache jar - 1.0.0-beta.46 + 1.0.0-beta.47 Microsoft Azure Apache Avro Serializer Library This package contains the Apache Avro serializer client plugin for azure-core. @@ -78,12 +78,12 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.azure azure-core-experimental - 1.0.0-beta.50 + 1.0.0-beta.51 diff --git a/sdk/core/azure-core-serializer-avro-jackson/pom.xml b/sdk/core/azure-core-serializer-avro-jackson/pom.xml index daa24e84ccff3..e4e8024dcf87e 100644 --- a/sdk/core/azure-core-serializer-avro-jackson/pom.xml +++ b/sdk/core/azure-core-serializer-avro-jackson/pom.xml @@ -70,12 +70,12 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.azure azure-core-experimental - 1.0.0-beta.50 + 1.0.0-beta.51 diff --git a/sdk/core/azure-core-serializer-json-gson/CHANGELOG.md b/sdk/core/azure-core-serializer-json-gson/CHANGELOG.md index 9518ac0e76fae..9aaa86e7ed26e 100644 --- a/sdk/core/azure-core-serializer-json-gson/CHANGELOG.md +++ b/sdk/core/azure-core-serializer-json-gson/CHANGELOG.md @@ -10,6 +10,14 @@ ### Other Changes +## 1.2.12 (2024-05-01) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + ## 1.2.11 (2024-04-05) ### Other Changes diff --git a/sdk/core/azure-core-serializer-json-gson/README.md b/sdk/core/azure-core-serializer-json-gson/README.md index f8799f41a3d5e..a60a21414ffe8 100644 --- a/sdk/core/azure-core-serializer-json-gson/README.md +++ b/sdk/core/azure-core-serializer-json-gson/README.md @@ -47,7 +47,7 @@ add the direct dependency to your project as follows. com.azure azure-core-serializer-json-gson - 1.2.11 + 1.2.12 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-serializer-json-gson/pom.xml b/sdk/core/azure-core-serializer-json-gson/pom.xml index b000b7daa3500..102cf05fa701c 100644 --- a/sdk/core/azure-core-serializer-json-gson/pom.xml +++ b/sdk/core/azure-core-serializer-json-gson/pom.xml @@ -79,7 +79,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.azure diff --git a/sdk/core/azure-core-serializer-json-jackson/CHANGELOG.md b/sdk/core/azure-core-serializer-json-jackson/CHANGELOG.md index f8597cdc0c242..f703eaca64047 100644 --- a/sdk/core/azure-core-serializer-json-jackson/CHANGELOG.md +++ b/sdk/core/azure-core-serializer-json-jackson/CHANGELOG.md @@ -10,6 +10,14 @@ ### Other Changes +## 1.4.12 (2024-05-01) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + ## 1.4.11 (2024-04-05) ### Other Changes diff --git a/sdk/core/azure-core-serializer-json-jackson/README.md b/sdk/core/azure-core-serializer-json-jackson/README.md index 59af1cd3b1f21..173e4e522853f 100644 --- a/sdk/core/azure-core-serializer-json-jackson/README.md +++ b/sdk/core/azure-core-serializer-json-jackson/README.md @@ -47,7 +47,7 @@ add the direct dependency to your project as follows. com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-serializer-json-jackson/pom.xml b/sdk/core/azure-core-serializer-json-jackson/pom.xml index c210f6d70a8e8..94ec30f14c4be 100644 --- a/sdk/core/azure-core-serializer-json-jackson/pom.xml +++ b/sdk/core/azure-core-serializer-json-jackson/pom.xml @@ -91,7 +91,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 diff --git a/sdk/core/azure-core-test/CHANGELOG.md b/sdk/core/azure-core-test/CHANGELOG.md index b7219e5c38b4e..2b0b848258316 100644 --- a/sdk/core/azure-core-test/CHANGELOG.md +++ b/sdk/core/azure-core-test/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.25.0-beta.1 (Unreleased) +## 1.26.0-beta.1 (Unreleased) ### Features Added @@ -10,7 +10,31 @@ ### Other Changes -## 1.24.1 (2024-04-23) +## 1.25.0 (2024-05-01) + +### Features Added + +- `TestContextManager` added `setTestIteration(Integer)` and `getTrackTestName`. +- Added annotations `LiveOnly` and `PlaybackOnly` to skip tests from running in other testing modes. +- Added `TestContextManagerParameterResolver` to manage resolving `TestContextManager` parameters. + +### Breaking Changes + +- `TestBase` no longer extends `BeforeEachCallback`. +- `TestBase.setupTest` now takes `TestContextManager` rather than `TestInfo`, which is provided by `TestContextManagerParameterResolver`. +- `TestBase.teardownTest` no longer takes a parameter. +- `TestProxyTestBase.setupTestProxy` no lnoger takes a parameter. +- `TestContextManager` no longer validates that a non-PLAYBACK test was ran in PLAYBACK mode, `TestBase` validates that now. +- `DoNotRecord` deprecated `skipInPlayback`, if a test should be skipped in PLAYBACK and shouldn't be recorded it should + be annotated with both `DoNotRecord` and `LiveOnly`. + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. + +## 1.24.2 (2024-04-23) ### Other Changes diff --git a/sdk/core/azure-core-test/README.md b/sdk/core/azure-core-test/README.md index bfefb7190cee5..3e26ac137ea75 100644 --- a/sdk/core/azure-core-test/README.md +++ b/sdk/core/azure-core-test/README.md @@ -35,7 +35,7 @@ To use this package, add the following to your _pom.xml_. com.azure azure-core-test - 1.24.1 + 1.25.0 ``` diff --git a/sdk/core/azure-core-test/checkstyle-suppressions.xml b/sdk/core/azure-core-test/checkstyle-suppressions.xml index 6f712669b1aea..9efcc47dd3d36 100644 --- a/sdk/core/azure-core-test/checkstyle-suppressions.xml +++ b/sdk/core/azure-core-test/checkstyle-suppressions.xml @@ -10,6 +10,9 @@ + + + diff --git a/sdk/core/azure-core-test/pom.xml b/sdk/core/azure-core-test/pom.xml index 9cea2e1bb5749..5bc7fade6ee19 100644 --- a/sdk/core/azure-core-test/pom.xml +++ b/sdk/core/azure-core-test/pom.xml @@ -13,7 +13,7 @@ com.azure azure-core-test jar - 1.25.0-beta.1 + 1.26.0-beta.1 Microsoft Azure Java Core Test Library This package contains core test types for Azure Java clients. @@ -72,7 +72,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 diff --git a/sdk/core/azure-core-test/spotbugs-exclude.xml b/sdk/core/azure-core-test/spotbugs-exclude.xml index 77cb7526832ac..e6918041c09b9 100644 --- a/sdk/core/azure-core-test/spotbugs-exclude.xml +++ b/sdk/core/azure-core-test/spotbugs-exclude.xml @@ -126,6 +126,10 @@ + + + + diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/AzureTestWatcher.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/AzureTestWatcher.java index 20e57b149134d..9b85d1a7f3c07 100644 --- a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/AzureTestWatcher.java +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/AzureTestWatcher.java @@ -7,8 +7,8 @@ import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; import org.junit.jupiter.api.extension.ExtensionContext; -import static com.azure.core.test.TestBase.getTestName; import static com.azure.core.test.TestBase.shouldLogExecutionStatus; +import static com.azure.core.test.implementation.TestingHelpers.getTestName; /** * JUnit 5 extension class which reports on testing running and simple metrics about the test such as run time. diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestBase.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestBase.java index c96e044dba26d..275bd286a1271 100644 --- a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestBase.java +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestBase.java @@ -4,10 +4,9 @@ import com.azure.core.http.HttpClient; import com.azure.core.http.HttpClientProvider; -import com.azure.core.test.annotation.RecordWithoutRequestBody; import com.azure.core.test.http.PlaybackClient; -import com.azure.core.test.implementation.TestIterationContext; import com.azure.core.test.implementation.TestingHelpers; +import com.azure.core.test.junitextensions.TestContextManagerParameterResolver; import com.azure.core.test.utils.HttpURLConnectionHttpClient; import com.azure.core.test.utils.TestResourceNamer; import com.azure.core.util.Configuration; @@ -20,30 +19,25 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInfo; -import org.junit.jupiter.api.extension.BeforeEachCallback; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.UncheckedIOException; -import java.lang.reflect.Method; import java.nio.file.Path; -import java.nio.file.Paths; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Locale; -import java.util.Objects; -import java.util.Optional; import java.util.ServiceLoader; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; -import static com.azure.core.test.utils.TestUtils.toURI; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Base class for running live and playback tests using {@link InterceptorManager}. */ -public abstract class TestBase implements BeforeEachCallback { +@ExtendWith(TestContextManagerParameterResolver.class) +public abstract class TestBase { private static final String AZURE_TEST_DEBUG = "AZURE_TEST_DEBUG"; // Environment variable name used to determine the TestMode. @@ -115,11 +109,6 @@ public abstract class TestBase implements BeforeEachCallback { */ protected TestContextManager testContextManager; - private ExtensionContext extensionContext; - - @RegisterExtension - final TestIterationContext testIterationContext = new TestIterationContext(); - private long testStartTimeMillis; /** @@ -137,41 +126,26 @@ public static void setupClass() { testMode = initializeTestMode(); } - @Override - public void beforeEach(ExtensionContext extensionContext) { - this.extensionContext = extensionContext; - } - /** * Sets-up the {@link TestBase#testResourceNamer} and {@link TestBase#interceptorManager} before each test case is * run. Then calls its implementing class to perform any other set-up commands. * - * @param testInfo {@link TestInfo} to retrieve test method name. + * @param testContextManager The {@link TestContextManager} managing information about this test. */ @BeforeEach - public void setupTest(TestInfo testInfo) { - TestMode localTestMode = testMode; - // for unit tests of playback/recording in azure-core-test, allow for changing the mode per-test. - if (testInfo.getTags().contains("Record")) { - localTestMode = TestMode.RECORD; - } else if (testInfo.getTags().contains("Playback")) { - localTestMode = TestMode.PLAYBACK; - } else if (testInfo.getTags().contains("Live")) { - localTestMode = TestMode.LIVE; - } + public void setupTest(TestContextManager testContextManager) { + this.testContextManager = testContextManager; + // This check used to happen in the constructor for TestContextManager, but due to how JUnit performs parameter + // resolution for @BeforeEach methods, we need to check here. If it was left in the constructor, the test would + // fail instead of being skipped. + assumeTrue(testContextManager.didTestRun(), "Test does not allow playback and was ran in 'TestMode.PLAYBACK'"); - String testName = getTestName(testInfo.getTestMethod(), testInfo.getDisplayName(), testInfo.getTestClass()); - Path testClassPath = Paths.get( - toURI(testInfo.getTestClass().get().getResource(testInfo.getTestClass().get().getSimpleName() + ".class"))); - this.testContextManager - = new TestContextManager(testInfo.getTestMethod().get(), localTestMode, isTestProxyEnabled(), - testInfo.getTestClass().get().getAnnotation(RecordWithoutRequestBody.class) != null, testClassPath); - testContextManager.setTestIteration(testIterationContext.getTestIteration()); - ThreadDumper.addRunningTest(testName); - logger.info("Test Mode: {}, Name: {}", localTestMode, testName); + ThreadDumper.addRunningTest(testContextManager.getTrackerTestName()); + logger.info("Test Mode: {}, Name: {}", testContextManager.getTestMode(), + testContextManager.getTrackerTestName()); if (shouldLogExecutionStatus()) { - System.out.println("Starting test " + testName + "."); + System.out.println("Starting test " + testContextManager.getTrackerTestName() + "."); testStartTimeMillis = System.currentTimeMillis(); } @@ -187,11 +161,11 @@ public void setupTest(TestInfo testInfo) { // The supplier/consumer are used to retrieve/store variables over the wire. testResourceNamer = new TestResourceNamer(testContextManager, interceptorManager.getProxyVariableConsumer(), interceptorManager.getProxyVariableSupplier()); - if (localTestMode == TestMode.PLAYBACK && !testContextManager.doNotRecordTest()) { + if (testContextManager.getTestMode() == TestMode.PLAYBACK && !testContextManager.doNotRecordTest()) { // We create the playback client here, so that it is available for returning recorded variables // in a shared @BeforeEach in a test class. interceptorManager.getPlaybackClient(); - } else if (localTestMode == TestMode.RECORD && !testContextManager.doNotRecordTest()) { + } else if (testContextManager.getTestMode() == TestMode.RECORD && !testContextManager.doNotRecordTest()) { // Similarly we create the record policy early so matchers/sanitizers can be added. interceptorManager.getRecordPolicy(); } @@ -203,23 +177,21 @@ public void setupTest(TestInfo testInfo) { /** * Disposes of {@link InterceptorManager} and its inheriting class' resources. - * - * @param testInfo the injected testInfo */ @AfterEach - public void teardownTest(TestInfo testInfo) { - String testName = getTestName(testInfo.getTestMethod(), testInfo.getDisplayName(), testInfo.getTestClass()); + public void teardownTest() { if (shouldLogExecutionStatus()) { if (testStartTimeMillis > 0) { long duration = System.currentTimeMillis() - testStartTimeMillis; - System.out.println("Finished test " + testName + " in " + duration + " ms."); + System.out + .println("Finished test " + testContextManager.getTrackerTestName() + " in " + duration + " ms."); } else { - System.out.println("Finished test " + testName + ", duration unknown."); + System.out.println("Finished test " + testContextManager.getTrackerTestName() + ", duration unknown."); } } if (testContextManager != null) { - ThreadDumper.removeRunningTest(testName); + ThreadDumper.removeRunningTest(testContextManager.getTrackerTestName()); if (testContextManager.didTestRun()) { afterTest(); @@ -244,12 +216,12 @@ public TestMode getTestMode() { * @deprecated This method is deprecated as JUnit 5 provides a simpler mechanism to get the test method name through * {@link TestInfo}. Keeping this for backward compatability of other client libraries that still override this * method. This method can be deleted when all client libraries remove this method. See {@link - * #setupTest(TestInfo)}. + * #setupTest(TestContextManager)}. */ @Deprecated protected String getTestName() { - if (extensionContext != null) { - return extensionContext.getTestMethod().map(Method::getName).orElse(null); + if (testContextManager != null) { + return testContextManager.getTestName(); } return null; } @@ -337,7 +309,7 @@ static TestMode initializeTestMode() { * Indicates whether the out of process test recording proxy is in use. * @return true if test proxy is to be used. */ - protected static boolean isTestProxyEnabled() { + public static boolean isTestProxyEnabled() { return enableTestProxy; } @@ -425,21 +397,6 @@ private static HttpClient getTestProxyHttpClient() { : httpClient); } - static String getTestName(Optional testMethod, String displayName, Optional> testClass) { - String testName = ""; - String fullyQualifiedTestName = ""; - if (testMethod.isPresent()) { - Method method = testMethod.get(); - String className = testClass.map(Class::getName).orElse(method.getDeclaringClass().getName()); - testName = method.getName(); - fullyQualifiedTestName = className + "." + testName; - } - - return Objects.equals(displayName, testName) - ? fullyQualifiedTestName - : fullyQualifiedTestName + "(" + displayName + ")"; - } - static boolean shouldLogExecutionStatus() { return Configuration.getGlobalConfiguration().get(AZURE_TEST_DEBUG, false); } diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestContextManager.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestContextManager.java index 9be0fa188d366..f70da33fb1497 100644 --- a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestContextManager.java +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestContextManager.java @@ -8,8 +8,6 @@ import java.lang.reflect.Method; import java.nio.file.Path; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - /** * This class handles managing context about a test, such as custom testing annotations and verifying whether the test * is capable of running. @@ -25,6 +23,7 @@ public class TestContextManager { private Integer testIteration; private final boolean skipRecordingRequestBody; private final Path testClassPath; + private final String trackerTestName; /** * Constructs a {@link TestContextManager} based on the test method. @@ -48,6 +47,24 @@ public TestContextManager(Method testMethod, TestMode testMode) { */ public TestContextManager(Method testMethod, TestMode testMode, boolean enableTestProxy, boolean recordWithoutRequestBodyClassAnnotation, Path testClassPath) { + this(testMethod, testMode, enableTestProxy, recordWithoutRequestBodyClassAnnotation, testClassPath, + testMethod.getName()); + } + + /** + * Constructs a {@link TestContextManager} based on the test method. + * + * @param testMethod Test method being ran. + * @param testMode The {@link TestMode} the test is running in. + * @param enableTestProxy True if the external test proxy is in use. + * @param recordWithoutRequestBodyClassAnnotation flag indicating if {@code RecordWithoutRequestBody} annotation + * present on test class. + * @param testClassPath the test class path + * @param trackerTestName The formatted test name used in logging and tracking its progress. + */ + @SuppressWarnings("deprecation") + public TestContextManager(Method testMethod, TestMode testMode, boolean enableTestProxy, + boolean recordWithoutRequestBodyClassAnnotation, Path testClassPath, String trackerTestName) { this.testName = testMethod.getName(); this.className = testMethod.getDeclaringClass().getSimpleName(); this.testMode = testMode; @@ -67,7 +84,7 @@ public TestContextManager(Method testMethod, TestMode testMode, boolean enableTe } this.testClassPath = testClassPath; this.testRan = !(skipInPlayback && testMode == TestMode.PLAYBACK); - assumeTrue(testRan, "Test does not allow playback and was ran in 'TestMode.PLAYBACK'"); + this.trackerTestName = trackerTestName; } /** @@ -154,7 +171,16 @@ public boolean didTestRun() { * * @param testIteration Test iteration. */ - void setTestIteration(Integer testIteration) { + public void setTestIteration(Integer testIteration) { this.testIteration = testIteration; } + + /** + * Gets the formatted name of the test used to log and track its progress. + * + * @return The formatted test name. + */ + public String getTrackerTestName() { + return trackerTestName; + } } diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestProxyTestBase.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestProxyTestBase.java index 563a24e6dcb7c..aab03bc1b838b 100644 --- a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestProxyTestBase.java +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestProxyTestBase.java @@ -5,7 +5,6 @@ import com.azure.core.test.utils.TestProxyManager; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.TestInfo; /** * Base class for running live and playback tests using test-proxy @@ -25,10 +24,9 @@ public TestProxyTestBase() { /** * Before tests are executed, determines the test mode by reading the {@code AZURE_TEST_MODE} environment variable. * If it is not set, {@link TestMode#PLAYBACK} - * @param testInfo {@link TestInfo} to retrieve test related metadata. */ @BeforeAll - public static void setupTestProxy(TestInfo testInfo) { + public static void setupTestProxy() { testMode = initializeTestMode(); if (isTestProxyEnabled() && (testMode == TestMode.PLAYBACK || testMode == TestMode.RECORD)) { TestProxyManager.startProxy(); diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/ThreadDumper.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/ThreadDumper.java index 9f179936095d8..ba24373b77591 100644 --- a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/ThreadDumper.java +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/ThreadDumper.java @@ -2,6 +2,7 @@ // Licensed under the MIT License. package com.azure.core.test; +import com.azure.core.test.implementation.TestingHelpers; import com.azure.core.util.logging.ClientLogger; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; @@ -153,6 +154,6 @@ static void removeRunningTest(String testName) { } private static String getFullTestName(ExtensionContext context) { - return TestBase.getTestName(context.getTestMethod(), context.getDisplayName(), context.getTestClass()); + return TestingHelpers.getTestName(context.getTestMethod(), context.getDisplayName(), context.getTestClass()); } } diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/DoNotRecord.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/DoNotRecord.java index 4522f0556f18a..8307646b3363d 100644 --- a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/DoNotRecord.java +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/DoNotRecord.java @@ -12,12 +12,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; /** - * Annotation given to some tests to indicate that network calls made during the test shouldn't be recorded. - * - *

- * Pass {@code true} for {@link #skipInPlayback() skipInPlayback} to indicate that the test shouldn't run when tests are - * ran in {@link TestMode#PLAYBACK}. A common case for setting this to {@code true} is when the test has either - * sensitive content that cannot be redacted or calls into code that cannot be mocked. + * Annotation given to some tests to indicate that network calls made during the test shouldn't be recorded or there + * won't be any network calls made during the test to prevent creating an empty recording. */ @Retention(RUNTIME) @Target({ METHOD }) @@ -27,6 +23,9 @@ * Returns whether the test will be ignored during a {@link TestMode#PLAYBACK playback} test run. * * @return Flag indicating if the test will be ignored during a playback test run. + * @deprecated If a test should not run in playback, use {@link LiveOnly} instead. This will be removed in a future + * release. */ + @Deprecated boolean skipInPlayback() default false; } diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/LiveOnly.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/LiveOnly.java new file mode 100644 index 0000000000000..798202051789f --- /dev/null +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/LiveOnly.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.core.test.annotation; + +import com.azure.core.test.junitextensions.LiveOnlyExtension; +import org.junit.jupiter.api.extension.ExtendWith; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotation to mark tests that should only be run in LIVE test mode. + */ +@Inherited +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE, ElementType.METHOD }) +@ExtendWith(LiveOnlyExtension.class) +public @interface LiveOnly { +} diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/PlaybackOnly.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/PlaybackOnly.java new file mode 100644 index 0000000000000..18773ea4cffd0 --- /dev/null +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/annotation/PlaybackOnly.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.core.test.annotation; + +import com.azure.core.test.junitextensions.PlaybackOnlyExtension; +import org.junit.jupiter.api.extension.ExtendWith; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotation to mark tests that should only be run in PLAYBACK test mode. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE, ElementType.METHOD }) +@ExtendWith(PlaybackOnlyExtension.class) +public @interface PlaybackOnly { + /** + * The expiry time of the PLAYBACK annotation in yyyy-MM-dd format. + *

+ * If the expiry time is not set, the test will only run in PLAYBACK mode. + *

+ * If the expiry time is set, the test will begin to fail instead of being skipped once the expiry time has passed. + * For example, if the expiry time is set to 2020-01-01, the test will be skipped in PLAYBACK mode until 2020-01-01. + * After 2020-01-01, the test will fail in PLAYBACK mode until the test is re-enabled. + * + * @return The expiry time of the PLAYBACK annotation. + */ + String expiryTime() default ""; +} diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/implementation/TestIterationContext.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/implementation/TestIterationContext.java deleted file mode 100644 index 042c936a3ba4e..0000000000000 --- a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/implementation/TestIterationContext.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.core.test.implementation; - -import org.junit.jupiter.api.extension.BeforeEachCallback; -import org.junit.jupiter.api.extension.ExtensionContext; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Hook into JUnit 5's test infrastructure which determines the test iteration. - */ -public final class TestIterationContext implements BeforeEachCallback { - private static final Pattern TEST_ITERATION_PATTERN = Pattern.compile("test-template-invocation:#(\\d+)"); - - private Integer testIteration; - - @Override - public void beforeEach(ExtensionContext extensionContext) { - Matcher matcher = TEST_ITERATION_PATTERN.matcher(extensionContext.getUniqueId()); - if (matcher.find()) { - testIteration = Integer.valueOf(matcher.group(1)); - } - } - - /** - * Gets the current test iteration. - * - * @return The current test iteration. - */ - public Integer getTestIteration() { - return testIteration; - } -} diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/implementation/TestingHelpers.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/implementation/TestingHelpers.java index d7b077037acab..7d23008a22fda 100644 --- a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/implementation/TestingHelpers.java +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/implementation/TestingHelpers.java @@ -11,7 +11,10 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.lang.reflect.Method; import java.util.Locale; +import java.util.Objects; +import java.util.Optional; /** * Implementation utility class. @@ -24,12 +27,9 @@ public final class TestingHelpers { public static final HttpHeaderName X_RECORDING_FILE_LOCATION = HttpHeaderName.fromString("x-base64-recording-file-location"); - /** - * Gets the {@link TestMode} being used to run tests. - * - * @return The {@link TestMode} being used to run tests. - */ - public static TestMode getTestMode() { + private static final TestMode TEST_MODE = initializeTestMode(); + + private static TestMode initializeTestMode() { final String azureTestMode = Configuration.getGlobalConfiguration().get(AZURE_TEST_MODE); if (azureTestMode != null) { @@ -45,6 +45,15 @@ public static TestMode getTestMode() { return TestMode.PLAYBACK; } + /** + * Gets the {@link TestMode} being used to run tests. + * + * @return The {@link TestMode} being used to run tests. + */ + public static TestMode getTestMode() { + return TEST_MODE; + } + /** * Copies the data from the input stream to the output stream. * @@ -60,4 +69,27 @@ public static void copy(InputStream source, OutputStream destination) throws IOE destination.write(buffer, 0, read); } } + + /** + * Gets the formated test name. + * + * @param testMethod The test method. + * @param displayName The test display name. + * @param testClass The test class. + * @return The formated test name. + */ + public static String getTestName(Optional testMethod, String displayName, Optional> testClass) { + String testName = ""; + String fullyQualifiedTestName = ""; + if (testMethod.isPresent()) { + Method method = testMethod.get(); + String className = testClass.map(Class::getName).orElse(method.getDeclaringClass().getName()); + testName = method.getName(); + fullyQualifiedTestName = className + "." + testName; + } + + return Objects.equals(displayName, testName) + ? fullyQualifiedTestName + : fullyQualifiedTestName + "(" + displayName + ")"; + } } diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/LiveOnlyExtension.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/LiveOnlyExtension.java new file mode 100644 index 0000000000000..e359d01e9fca2 --- /dev/null +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/LiveOnlyExtension.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.core.test.junitextensions; + +import com.azure.core.test.TestMode; +import com.azure.core.test.annotation.LiveOnly; +import com.azure.core.test.implementation.TestingHelpers; +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; + +import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation; + +/** + * Extension to mark tests that should only be run in LIVE test mode. + */ +public class LiveOnlyExtension implements ExecutionCondition { + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + LiveOnly liveOnly = findAnnotation(context.getElement(), LiveOnly.class).orElse(null); + if (liveOnly != null) { + // Only disable evaluation if the annotation is set and the test mode is not live. + TestMode testMode = TestingHelpers.getTestMode(); + return (testMode != TestMode.LIVE) + ? ConditionEvaluationResult.disabled("LiveOnly annotation set and test ignored in " + testMode) + : ConditionEvaluationResult.enabled("LiveOnly annotation set and test enabled in " + testMode); + } + + return ConditionEvaluationResult.enabled("LiveOnly annotation not set."); + } +} diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/PlaybackOnlyExtension.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/PlaybackOnlyExtension.java new file mode 100644 index 0000000000000..087260c1615dd --- /dev/null +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/PlaybackOnlyExtension.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.core.test.junitextensions; + +import com.azure.core.test.TestMode; +import com.azure.core.test.annotation.PlaybackOnly; +import com.azure.core.test.implementation.TestingHelpers; +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation; + +/** + * Extension to mark tests that should only be run in PLAYBACK test mode. + */ +public class PlaybackOnlyExtension implements ExecutionCondition { + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + PlaybackOnly playbackOnly = findAnnotation(context.getElement(), PlaybackOnly.class).orElse(null); + if (playbackOnly != null) { + // Check if the Playback only time has expired. + validateExpiryTime(playbackOnly); + + // Only disable evaluation if the annotation is set and the test mode is not playback. + TestMode testMode = TestingHelpers.getTestMode(); + return (testMode != TestMode.PLAYBACK) + ? ConditionEvaluationResult.disabled("PlaybackOnly annotation set and test ignored in " + testMode) + : ConditionEvaluationResult.enabled("PlaybackOnly annotation set and test enabled in " + testMode); + } + + return ConditionEvaluationResult.enabled("PlaybackOnly annotation not set."); + } + + private static void validateExpiryTime(PlaybackOnly annotation) { + String expiryStr = annotation.expiryTime(); + if ("".equals(expiryStr)) { + return; + } + + LocalDate expiry = LocalDate.parse(expiryStr, DateTimeFormatter.ISO_LOCAL_DATE); + LocalDate now = LocalDate.now(); + if (now.isAfter(expiry)) { + throw new RuntimeException("PlaybackOnly has expired. Test must be re-enabled"); + } + } + +} diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/TestContextManagerParameterResolver.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/TestContextManagerParameterResolver.java new file mode 100644 index 0000000000000..ffad3605626e6 --- /dev/null +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/TestContextManagerParameterResolver.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.core.test.junitextensions; + +import com.azure.core.test.TestBase; +import com.azure.core.test.TestContextManager; +import com.azure.core.test.TestMode; +import com.azure.core.test.annotation.RecordWithoutRequestBody; +import com.azure.core.test.implementation.TestingHelpers; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.azure.core.test.TestBase.isTestProxyEnabled; +import static com.azure.core.test.implementation.TestingHelpers.getTestName; +import static com.azure.core.test.utils.TestUtils.toURI; + +/** + * A {@link ParameterResolver} implementation that resolves {@link TestContextManager} parameters. + *

+ * Used by the {@link TestBase#setupTest(TestContextManager)} method. + */ +public final class TestContextManagerParameterResolver implements ParameterResolver { + private static final Pattern TEST_ITERATION_PATTERN = Pattern.compile("test-template-invocation:#(\\d+)"); + + /** + * Creates a new instance of TestContextManagerParameterResolver. + */ + public TestContextManagerParameterResolver() { + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) + throws ParameterResolutionException { + return parameterContext.getParameter().getType() == TestContextManager.class; + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) + throws ParameterResolutionException { + TestMode localTestMode = TestingHelpers.getTestMode(); + // for unit tests of playback/recording in azure-core-test, allow for changing the mode per-test. + if (context.getTags().contains("Record")) { + localTestMode = TestMode.RECORD; + } else if (context.getTags().contains("Playback")) { + localTestMode = TestMode.PLAYBACK; + } else if (context.getTags().contains("Live")) { + localTestMode = TestMode.LIVE; + } + + String trackerTestName = getTestName(context.getTestMethod(), context.getDisplayName(), context.getTestClass()); + Path testClassPath = Paths.get( + toURI(context.getTestClass().get().getResource(context.getTestClass().get().getSimpleName() + ".class"))); + + TestContextManager testContextManager = new TestContextManager(context.getTestMethod().get(), localTestMode, + isTestProxyEnabled(), context.getTestClass().get().getAnnotation(RecordWithoutRequestBody.class) != null, + testClassPath, trackerTestName); + testContextManager.setTestIteration(getTestIteration(context)); + + return testContextManager; + } + + private static Integer getTestIteration(ExtensionContext extensionContext) { + if (extensionContext == null) { + return null; + } + + Matcher matcher = TEST_ITERATION_PATTERN.matcher(extensionContext.getUniqueId()); + return matcher.find() ? Integer.valueOf(matcher.group(1)) : null; + } +} diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/package-info.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/package-info.java new file mode 100644 index 0000000000000..2c6946b1b3596 --- /dev/null +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/junitextensions/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * This package contains classes that implement JUnit extension points. + */ +package com.azure.core.test.junitextensions; diff --git a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java index 3a6503d9349f3..d5c98048459a8 100644 --- a/sdk/core/azure-core-test/src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java +++ b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java @@ -78,10 +78,15 @@ public RecordNetworkCallPolicy(RecordedData recordedData, List process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { // If TEST_MODE isn't RECORD do not record. - if (TestingHelpers.getTestMode() != TestMode.RECORD) { + if (getTestMode() != TestMode.RECORD) { return next.process(); } diff --git a/sdk/core/azure-core-test/src/main/java/module-info.java b/sdk/core/azure-core-test/src/main/java/module-info.java index 3491a5b859227..fdd57e3585627 100644 --- a/sdk/core/azure-core-test/src/main/java/module-info.java +++ b/sdk/core/azure-core-test/src/main/java/module-info.java @@ -7,6 +7,7 @@ requires com.fasterxml.jackson.dataformat.xml; requires org.junit.jupiter.api; requires org.junit.jupiter.params; + requires org.junit.platform.commons; requires reactor.test; requires java.management; requires java.net.http; @@ -23,16 +24,19 @@ exports com.azure.core.test; exports com.azure.core.test.annotation; exports com.azure.core.test.http; + exports com.azure.core.test.junitextensions; exports com.azure.core.test.models; exports com.azure.core.test.policy; exports com.azure.core.test.utils; - opens com.azure.core.test to com.fasterxml.jackson.databind, org.junit.platform.commons; opens com.azure.core.test.models to com.fasterxml.jackson.databind; - opens com.azure.core.test.annotation to org.junit.platform.commons; opens com.azure.core.test.implementation to com.fasterxml.jackson.databind, com.azure.core, org.junit.platform.commons; opens com.azure.core.test.implementation.entities to com.fasterxml.jackson.databind, com.azure.core; + opens com.azure.core.test to com.azure.core, com.fasterxml.jackson.databind, org.junit.platform.commons; + opens com.azure.core.test.junitextensions + to com.azure.core, com.fasterxml.jackson.databind, org.junit.platform.commons; + opens com.azure.core.test.annotation to com.azure.core, com.fasterxml.jackson.databind, org.junit.platform.commons; uses com.azure.core.http.HttpClientProvider; } diff --git a/sdk/core/azure-core-test/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/sdk/core/azure-core-test/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension index b3b12ece048ff..a15969d5f857d 100644 --- a/sdk/core/azure-core-test/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension +++ b/sdk/core/azure-core-test/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension @@ -1,2 +1,5 @@ com.azure.core.test.AzureTestWatcher com.azure.core.test.ThreadDumper +com.azure.core.test.junitextensions.LiveOnlyExtension +com.azure.core.test.junitextensions.PlaybackOnlyExtension +com.azure.core.test.junitextensions.TestContextManagerParameterResolver diff --git a/sdk/core/azure-core-test/src/test/java/com/azure/core/test/FakeTestClass.java b/sdk/core/azure-core-test/src/test/java/com/azure/core/test/FakeTestClass.java index 7dfe22900ffb5..439d83651b863 100644 --- a/sdk/core/azure-core-test/src/test/java/com/azure/core/test/FakeTestClass.java +++ b/sdk/core/azure-core-test/src/test/java/com/azure/core/test/FakeTestClass.java @@ -23,6 +23,7 @@ public void testWithDoNotRecordRunInPlayback() { } + @SuppressWarnings("deprecation") @DoNotRecord(skipInPlayback = true) public void testWithDoNotRecordSkipInPlayback() { } diff --git a/sdk/core/azure-core-test/src/test/java/com/azure/core/test/TestContextManagerTests.java b/sdk/core/azure-core-test/src/test/java/com/azure/core/test/TestContextManagerTests.java index 07e6dccc7fd47..4fce33efb5eac 100644 --- a/sdk/core/azure-core-test/src/test/java/com/azure/core/test/TestContextManagerTests.java +++ b/sdk/core/azure-core-test/src/test/java/com/azure/core/test/TestContextManagerTests.java @@ -7,7 +7,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import org.opentest4j.TestAbortedException; import java.lang.reflect.Method; @@ -15,7 +14,6 @@ import static com.azure.core.test.FakeTestClass.DONOTRECORD_SKIPINPLAYBACK; import static com.azure.core.test.FakeTestClass.METHOD_WITHOUT_DONOTRECORD; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -60,10 +58,12 @@ public void testWithDoNotRecordRunInPlayback(TestMode testMode) { public void testWithDoNotRecordSkipInPlayback() { Method testMethod = DONOTRECORD_SKIPINPLAYBACK; - assertThrows(TestAbortedException.class, - () -> new TestContextManager(testMethod, TestMode.PLAYBACK, false, false, null)); + TestContextManager testContextManager + = new TestContextManager(testMethod, TestMode.PLAYBACK, false, false, null); + assertTrue(testContextManager.doNotRecordTest()); + assertFalse(testContextManager.didTestRun()); - TestContextManager testContextManager = new TestContextManager(testMethod, TestMode.LIVE, false, false, null); + testContextManager = new TestContextManager(testMethod, TestMode.LIVE, false, false, null); assertTrue(testContextManager.doNotRecordTest()); assertTrue(testContextManager.didTestRun()); diff --git a/sdk/core/azure-core-test/src/test/java/com/azure/core/test/implementation/MockExtensionContext.java b/sdk/core/azure-core-test/src/test/java/com/azure/core/test/implementation/MockExtensionContext.java index 0492a0e48e4d1..124ecf889e23e 100644 --- a/sdk/core/azure-core-test/src/test/java/com/azure/core/test/implementation/MockExtensionContext.java +++ b/sdk/core/azure-core-test/src/test/java/com/azure/core/test/implementation/MockExtensionContext.java @@ -38,7 +38,7 @@ public ExtensionContext getRoot() { @Override public String getUniqueId() { - return null; + return ""; } @Override diff --git a/sdk/core/azure-core-test/src/test/java/com/azure/core/test/policy/RecordNetworkCallPolicyTests.java b/sdk/core/azure-core-test/src/test/java/com/azure/core/test/policy/RecordNetworkCallPolicyTests.java index 6fe051258e4bf..33adbfdeb94a1 100644 --- a/sdk/core/azure-core-test/src/test/java/com/azure/core/test/policy/RecordNetworkCallPolicyTests.java +++ b/sdk/core/azure-core-test/src/test/java/com/azure/core/test/policy/RecordNetworkCallPolicyTests.java @@ -7,13 +7,10 @@ import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.HttpRequest; +import com.azure.core.test.TestMode; import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.test.implementation.TestingHelpers; import com.azure.core.test.models.NetworkCallRecord; import com.azure.core.test.models.RecordedData; -import com.azure.core.util.Configuration; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.parallel.Isolated; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -28,22 +25,14 @@ @Isolated public class RecordNetworkCallPolicyTests { - private static String azureTestRecordMode; - - @SuppressWarnings("deprecation") - @BeforeAll - public static void beforeAll() { - azureTestRecordMode = Configuration.getGlobalConfiguration().get(TestingHelpers.AZURE_TEST_MODE); - Configuration.getGlobalConfiguration().put(TestingHelpers.AZURE_TEST_MODE, "RECORD"); - } + private static final class AlwaysRecordRecordNetworkCallPolicy extends RecordNetworkCallPolicy { + @Override + TestMode getTestMode() { + return TestMode.RECORD; + } - @SuppressWarnings("deprecation") - @AfterAll - public static void afterAll() { - if (azureTestRecordMode == null) { - Configuration.getGlobalConfiguration().remove(TestingHelpers.AZURE_TEST_MODE); - } else { - Configuration.getGlobalConfiguration().put(TestingHelpers.AZURE_TEST_MODE, azureTestRecordMode); + AlwaysRecordRecordNetworkCallPolicy(RecordedData recordedData) { + super(recordedData); } } @@ -51,9 +40,10 @@ public static void afterAll() { @MethodSource("sigValueIsRedactedSupplier") public void sigValueIsRedacted(String requestUrl, String expectedRedactedUrl) { RecordedData recordedData = new RecordedData(); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new RecordNetworkCallPolicy(recordedData)) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .build(); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new AlwaysRecordRecordNetworkCallPolicy(recordedData)) + .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) + .build(); StepVerifier.create(pipeline.send(new HttpRequest(HttpMethod.GET, requestUrl))) .assertNext(response -> assertEquals(200, response.getStatusCode())) diff --git a/sdk/core/azure-core-tracing-opentelemetry-samples/pom.xml b/sdk/core/azure-core-tracing-opentelemetry-samples/pom.xml index 75d406526d855..daebbbff7e389 100644 --- a/sdk/core/azure-core-tracing-opentelemetry-samples/pom.xml +++ b/sdk/core/azure-core-tracing-opentelemetry-samples/pom.xml @@ -40,14 +40,14 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.46 + 1.0.0-beta.47 com.azure azure-core-http-netty - 1.15.0-beta.1 + 1.16.0-beta.1 test @@ -77,7 +77,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md b/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md index 5a18b7317e333..81b657de879c5 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md +++ b/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md @@ -1,17 +1,32 @@ # Release History -## 1.0.0-beta.46 (Unreleased) +## 1.0.0-beta.47 (Unreleased) ### Features Added ### Breaking Changes +### Bugs Fixed + +### Other Changes + +## 1.0.0-beta.46 (2024-05-01) + +### Breaking Changes + - Added default query params sanitization for HTTP spans. ### Bugs Fixed +- Fixed explicit context propagation when running in javaagent. ([#39602](https://github.com/Azure/azure-sdk-for-java/pull/39602)) + ### Other Changes +#### Dependency Updates + +- Upgraded `azure-core` from `1.48.0` to `1.49.0`. +- Upgraded OpenTelemetry from `1.36.0` to `1.37.0`. + ## 1.0.0-beta.45 (2024-04-05) ### Bugs Fixed diff --git a/sdk/core/azure-core-tracing-opentelemetry/README.md b/sdk/core/azure-core-tracing-opentelemetry/README.md index cc4b334d65631..6dcdc7ff2e9ae 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/README.md +++ b/sdk/core/azure-core-tracing-opentelemetry/README.md @@ -51,7 +51,7 @@ To enable Azure SDK tracing, add the latest `com.azure:azure-core-tracing-opente com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opentelemetry/pom.xml b/sdk/core/azure-core-tracing-opentelemetry/pom.xml index 451e7f6bc5c5e..ceb5e0d937694 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/pom.xml +++ b/sdk/core/azure-core-tracing-opentelemetry/pom.xml @@ -12,7 +12,7 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.46 + 1.0.0-beta.47 Microsoft Azure OpenTelemetry tracing plugin This package contains the OpenTelemetry tracing plugin for Azure client libraries. @@ -67,7 +67,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.google.code.findbugs @@ -86,19 +86,19 @@ com.azure azure-core-experimental - 1.0.0-beta.50 + 1.0.0-beta.51 test com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test com.azure azure-core-http-netty - 1.15.0-beta.1 + 1.16.0-beta.1 test diff --git a/sdk/core/azure-core-version-tests/pom.xml b/sdk/core/azure-core-version-tests/pom.xml index 943210f67ce53..2219f6dbd19ab 100644 --- a/sdk/core/azure-core-version-tests/pom.xml +++ b/sdk/core/azure-core-version-tests/pom.xml @@ -62,7 +62,7 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.azure @@ -113,7 +113,7 @@ com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 io.projectreactor diff --git a/sdk/core/azure-core/CHANGELOG.md b/sdk/core/azure-core/CHANGELOG.md index 243683a70ca64..ae330f04e5088 100644 --- a/sdk/core/azure-core/CHANGELOG.md +++ b/sdk/core/azure-core/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.49.0-beta.1 (Unreleased) +## 1.50.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,21 @@ ### Other Changes +## 1.49.0 (2024-05-01) + +### Features Added + +- Added `SharedExecutorService` which acts as a global thread pool for the SDKs to use. ([#38860](https://github.com/Azure/azure-sdk-for-java/pull/38860)) + +### Bugs Fixed + +- Fixed an issue where HTTP responses would not be logged if the response body was never consumed. ([#39964](https://github.com/Azure/azure-sdk-for-java/pull/39964)) + +### Other Changes + +- Added default time to `CloudEvent` to be the current time if not set. ([#39751](https://github.com/Azure/azure-sdk-for-java/pull/39751)) +- Deprecated APIs exposing Jackson types. ([#39563](https://github.com/Azure/azure-sdk-for-java/pull/39563)) + ## 1.48.0 (2024-04-05) ### Features Added diff --git a/sdk/core/azure-core/README.md b/sdk/core/azure-core/README.md index fe75b70cb8511..929e8996206c2 100644 --- a/sdk/core/azure-core/README.md +++ b/sdk/core/azure-core/README.md @@ -65,7 +65,7 @@ add the direct dependency to your project as follows. com.azure azure-core - 1.48.0 + 1.49.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core/pom.xml b/sdk/core/azure-core/pom.xml index f70c60e466569..f3ca63be12c6a 100644 --- a/sdk/core/azure-core/pom.xml +++ b/sdk/core/azure-core/pom.xml @@ -15,7 +15,7 @@ com.azure azure-core jar - 1.49.0-beta.1 + 1.50.0-beta.1 Microsoft Azure Java Core Library This package contains core types for Azure Java clients. diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogDetailLevel.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogDetailLevel.java index 52830ce1ba76b..e9100664b63fd 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogDetailLevel.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogDetailLevel.java @@ -54,14 +54,17 @@ public enum HttpLogDetailLevel { /** * Logs everything in BASIC, plus all the request and response body. - * Note that only payloads in plain text or plain text encoded in GZIP - * will be logged. + * Note that only payloads in plain text or plain text encoded in GZIP will be logged. + * The response body will be buffered into memory even if it is never consumed by an application, possibly impacting + * performance. */ BODY, /** * Logs everything in HEADERS and BODY. * Values of the headers will be logged only for allowed headers. See {@link HttpLogOptions#getAllowedHeaderNames()}. + * The response body will be buffered into memory even if it is never consumed by an application, possibly impacting + * performance. */ BODY_AND_HEADERS; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java index 655cdc09f6549..57ed2e7282e0f 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java @@ -36,8 +36,6 @@ import java.io.IOException; import java.io.UncheckedIOException; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Locale; @@ -57,6 +55,10 @@ *

This class is useful when you need to log HTTP traffic for debugging or auditing purposes. It allows you to * control the amount of information that is logged, including the URL, headers, and body of requests and responses.

* + *

NOTE: Enabling body logging (using the {@link HttpLogDetailLevel#BODY BODY} or + * {@link HttpLogDetailLevel#BODY_AND_HEADERS BODY_AND_HEADERS} levels) will buffer the response body into memory even + * if it is never consumed by your application, possibly impacting performance.

+ * *

Code sample:

* *

In this example, an {@code HttpLogOptions} is created and the log level is set to @@ -226,6 +228,7 @@ private final class DefaultHttpRequestLogger implements HttpRequestLogger { @Override public Mono logRequest(ClientLogger logger, HttpRequestLoggingContext loggingOptions) { logRequestSync(logger, loggingOptions); + return Mono.empty(); } @@ -240,11 +243,13 @@ private void log(LogLevel logLevel, ClientLogger logger, HttpRequestLoggingConte } final HttpRequest request = loggingOptions.getHttpRequest(); + LoggingEventBuilder logBuilder = getLogBuilder(logLevel, logger).addKeyValue(LoggingKeys.HTTP_METHOD_KEY, request.getHttpMethod()) .addKeyValue(LoggingKeys.URL_KEY, urlSanitizer.getRedactedUrl(request.getUrl())); Integer retryCount = loggingOptions.getTryCount(); + if (retryCount != null) { logBuilder.addKeyValue(LoggingKeys.TRY_COUNT_KEY, retryCount); } @@ -255,16 +260,21 @@ private void log(LogLevel logLevel, ClientLogger logger, HttpRequestLoggingConte } Long contentLength = getAndLogContentLength(request.getHeaders(), logBuilder, logger); + if (request.getBody() == null) { logBuilder.log(REQUEST_LOG_MESSAGE); + return; } String contentType = request.getHeaders().getValue(HttpHeaderName.CONTENT_TYPE); + if (httpLogDetailLevel.shouldLogBody() && shouldBodyBeLogged(contentType, contentLength)) { // shouldBodyBeLogged ensures contentLength is not null and within limits. int contentLengthInt = contentLength.intValue(); + logBody(request, contentLengthInt, logBuilder, logger, contentType); + return; } @@ -276,19 +286,23 @@ private void logBody(HttpRequest request, int contentLength, LoggingEventBuilder String contentType) { BinaryData data = request.getBodyAsBinaryData(); BinaryDataContent content = BinaryDataHelper.getContent(data); + if (content instanceof StringContent || content instanceof ByteBufferContent || content instanceof SerializableContent || content instanceof ByteArrayContent) { + logBody(logBuilder, logger, contentType, content.toString()); } else if (content instanceof InputStreamContent) { // TODO (limolkova) Implement sync version with logging stream wrapper byte[] contentBytes = content.toBytes(); + request.setBody(contentBytes); logBody(logBuilder, logger, contentType, new String(contentBytes, StandardCharsets.UTF_8)); } else { // Add non-mutating operators to the data stream. AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); + request.setBody(Flux.using(() -> stream, s -> content.toFluxByteBuffer().doOnNext(byteBuffer -> { try { ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), s); @@ -308,28 +322,36 @@ private final class DefaultHttpResponseLogger implements HttpResponseLogger { @Override public Mono logResponse(ClientLogger logger, HttpResponseLoggingContext loggingOptions) { final LogLevel logLevel = getLogLevel(loggingOptions); - final HttpResponse response = loggingOptions.getHttpResponse(); + HttpResponse response = loggingOptions.getHttpResponse(); if (!logger.canLogAtLevel(logLevel) || httpLogDetailLevel == HttpLogDetailLevel.NONE) { return Mono.just(response); } LoggingEventBuilder logBuilder = getLogBuilder(logLevel, logger); + addBasicResponseProperties(logger, loggingOptions, response, logBuilder); + Long contentLength = getAndLogContentLength(response.getHeaders(), logBuilder, logger); + Mono responseMono = Mono.just(response); if (httpLogDetailLevel.shouldLogBody()) { String contentTypeHeader = response.getHeaderValue(HttpHeaderName.CONTENT_TYPE); + if (shouldBodyBeLogged(contentTypeHeader, contentLength)) { - // shouldBodyBeLogged ensures contentLength is not null and within limits. - int contentLengthInt = contentLength.intValue(); - return Mono.just(new LoggingHttpResponse(response, logBuilder, logger, contentLengthInt, - contentTypeHeader, prettyPrintBody)); + // Make sure we buffer the response body to avoid keeping the connection open. + final HttpResponse bufferedResponse = response.buffer(); + + responseMono = FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).map(bytes -> { + logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, + contentTypeHeader, new String(bytes, StandardCharsets.UTF_8))); + + return bufferedResponse; + }); } } - logBuilder.log(RESPONSE_LOG_MESSAGE); - return Mono.just(response); + return responseMono.doOnNext(ignored -> logBuilder.log(RESPONSE_LOG_MESSAGE)); } private void logHeaders(ClientLogger logger, HttpResponse response, LoggingEventBuilder logBuilder) { @@ -357,27 +379,32 @@ private void addBasicResponseProperties(ClientLogger logger, HttpResponseLogging @Override public HttpResponse logResponseSync(ClientLogger logger, HttpResponseLoggingContext loggingOptions) { final LogLevel logLevel = getLogLevel(loggingOptions); - final HttpResponse response = loggingOptions.getHttpResponse(); + HttpResponse response = loggingOptions.getHttpResponse(); if (!logger.canLogAtLevel(logLevel)) { return response; } LoggingEventBuilder logBuilder = getLogBuilder(logLevel, logger); + addBasicResponseProperties(logger, loggingOptions, response, logBuilder); + Long contentLength = getAndLogContentLength(response.getHeaders(), logBuilder, logger); if (httpLogDetailLevel.shouldLogBody()) { String contentTypeHeader = response.getHeaderValue(HttpHeaderName.CONTENT_TYPE); + if (shouldBodyBeLogged(contentTypeHeader, contentLength)) { - // shouldBodyBeLogged ensures contentLength is not null and within limits. - int contentLengthInt = contentLength.intValue(); - return new LoggingHttpResponse(response, logBuilder, logger, contentLengthInt, contentTypeHeader, - prettyPrintBody); + // Make sure we buffer the response body to avoid keeping the connection open. + response = response.buffer(); + + logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, + contentTypeHeader, response.getBodyAsBinaryData().toString())); } } logBuilder.log(RESPONSE_LOG_MESSAGE); + return response; } } @@ -401,12 +428,14 @@ private static void addHeadersToLogMessage(Set allowedHeaderNames, HttpH if (CONTENT_LENGTH_KEY.equals(key)) { return; } + if (allowedHeaderNames.contains(key)) { logBuilder.addKeyValue(value.getName(), value.getValue()); } else if (!disableRedactedHeaderLogging) { if (redactedHeaders.length() > 0) { redactedHeaders.append(','); } + redactedHeaders.append(value.getName()); } }); @@ -432,9 +461,11 @@ private static void addHeadersToLogMessage(Set allowedHeaderNames, HttpH private static String prettyPrintIfNeeded(ClientLogger logger, boolean prettyPrintBody, String contentType, String body) { String result = body; + if (prettyPrintBody && contentType != null && (contentType.startsWith(ContentType.APPLICATION_JSON) || contentType.startsWith("text/json"))) { + try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); @@ -442,6 +473,7 @@ private static String prettyPrintIfNeeded(ClientLogger logger, boolean prettyPri logger.log(LogLevel.WARNING, () -> "Failed to pretty print JSON", e); } } + return result; } @@ -456,18 +488,22 @@ private static String prettyPrintIfNeeded(ClientLogger logger, boolean prettyPri */ private Long getAndLogContentLength(HttpHeaders headers, LoggingEventBuilder logBuilder, ClientLogger logger) { String contentLengthString = headers.getValue(HttpHeaderName.CONTENT_LENGTH); + if (CoreUtils.isNullOrEmpty(contentLengthString)) { return null; } try { Long contentLength = Long.parseLong(contentLengthString); + logBuilder.addKeyValue(CONTENT_LENGTH_KEY, contentLength); + return contentLength; } catch (NumberFormatException e) { logger.atInfo() .addKeyValue(CONTENT_LENGTH_KEY, contentLengthString) .log("Could not parse the HTTP header content-length", e); + return null; } } @@ -499,6 +535,7 @@ private static boolean shouldBodyBeLogged(String contentTypeHeader, Long content */ private static Integer getRequestRetryCount(Context context) { Object rawRetryCount = context.getData(RETRY_COUNT_CONTEXT).orElse(null); + if (rawRetryCount == null) { return null; } @@ -509,6 +546,7 @@ private static Integer getRequestRetryCount(Context context) { LOGGER.atInfo() .addKeyValue(LoggingKeys.TRY_COUNT_KEY, rawRetryCount) .log("Could not parse the request retry count."); + return null; } } @@ -521,6 +559,7 @@ private static ClientLogger getOrCreateMethodLogger(Context context) { // Context rather than the name of the logger. This way HttpLoggingPolicy doesn't need to keep track of // ClientLogger instances. ClientLogger logger = (ClientLogger) context.getData("caller-method-logger").orElse(null); + if (logger != null) { return logger; } @@ -550,92 +589,4 @@ private static LoggingEventBuilder getLogBuilder(LogLevel logLevel, ClientLogger return logger.atVerbose(); } } - - private static final class LoggingHttpResponse extends HttpResponse { - private final HttpResponse actualResponse; - private final LoggingEventBuilder logBuilder; - private final int contentLength; - private final ClientLogger logger; - private final boolean prettyPrintBody; - private final String contentTypeHeader; - - private LoggingHttpResponse(HttpResponse actualResponse, LoggingEventBuilder logBuilder, ClientLogger logger, - int contentLength, String contentTypeHeader, boolean prettyPrintBody) { - super(actualResponse.getRequest()); - this.actualResponse = actualResponse; - this.logBuilder = logBuilder; - this.logger = logger; - this.contentLength = contentLength; - this.contentTypeHeader = contentTypeHeader; - this.prettyPrintBody = prettyPrintBody; - } - - @Override - public int getStatusCode() { - return actualResponse.getStatusCode(); - } - - @Override - @Deprecated - public String getHeaderValue(String name) { - return actualResponse.getHeaderValue(name); - } - - @Override - public String getHeaderValue(HttpHeaderName headerName) { - return actualResponse.getHeaderValue(headerName); - } - - @Override - public HttpHeaders getHeaders() { - return actualResponse.getHeaders(); - } - - @Override - public Flux getBody() { - AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); - - return Flux.using(() -> stream, s -> actualResponse.getBody().doOnNext(byteBuffer -> { - try { - ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), s); - } catch (IOException ex) { - throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); - } - }), s -> doLog(s.toString(StandardCharsets.UTF_8))); - } - - @Override - public Mono getBodyAsByteArray() { - return FluxUtil.collectBytesFromNetworkResponse(getBody(), actualResponse.getHeaders()); - } - - @Override - public Mono getBodyAsString() { - return getBodyAsByteArray().map(String::new); - } - - @Override - public Mono getBodyAsString(Charset charset) { - return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); - } - - @Override - public BinaryData getBodyAsBinaryData() { - BinaryData content = actualResponse.getBodyAsBinaryData(); - doLog(content.toString()); - return content; - } - - @Override - public void close() { - actualResponse.close(); - } - - private void doLog(String body) { - logBuilder - .addKeyValue(LoggingKeys.BODY_KEY, - prettyPrintIfNeeded(logger, prettyPrintBody, contentTypeHeader, body)) - .log(RESPONSE_LOG_MESSAGE); - } - } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/ImplUtils.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/ImplUtils.java index edc76a168d8ae..dde7b00f3fbd9 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/ImplUtils.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/ImplUtils.java @@ -9,6 +9,7 @@ import com.azure.core.http.policy.RetryStrategy; import com.azure.core.implementation.accesshelpers.ExponentialBackoffAccessHelper; import com.azure.core.implementation.accesshelpers.FixedDelayAccessHelper; +import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import com.azure.core.util.DateTimeRfc1123; import com.azure.core.util.FluxUtil; @@ -497,6 +498,91 @@ public static T getResultWithTimeout(Future future, long timeoutInMillis) } } + /** + * Helper method that safely adds a {@link Runtime#addShutdownHook(Thread)} to the JVM that will run when the JVM is + * shutting down. + *

+ * {@link Runtime#addShutdownHook(Thread)} checks for security privileges and will throw an exception if the proper + * security isn't available. So, if running with a security manager, setting + * {@code AZURE_ENABLE_SHUTDOWN_HOOK_WITH_PRIVILEGE} to true will have this method use access controller to add + * the shutdown hook with privileged permissions. + *

+ * If {@code shutdownThread} is null, no shutdown hook will be added and this method will return null. + * + * @param shutdownThread The {@link Thread} that will be added as a + * {@link Runtime#addShutdownHook(Thread) shutdown hook}. + * @return The {@link Thread} that was passed in. + */ + @SuppressWarnings({ "deprecation", "removal" }) + public static Thread addShutdownHookSafely(Thread shutdownThread) { + if (shutdownThread == null) { + return null; + } + + if (ShutdownHookAccessHelperHolder.shutdownHookAccessHelper) { + java.security.AccessController.doPrivileged((java.security.PrivilegedAction) () -> { + Runtime.getRuntime().addShutdownHook(shutdownThread); + return null; + }); + } else { + Runtime.getRuntime().addShutdownHook(shutdownThread); + } + + return shutdownThread; + } + + /** + * Helper method that safely removes a {@link Runtime#removeShutdownHook(Thread)} from the JVM. + *

+ * {@link Runtime#removeShutdownHook(Thread)} checks for security privileges and will throw an exception if the + * proper security isn't available. So, if running with a security manager, setting + * {@code AZURE_ENABLE_SHUTDOWN_HOOK_WITH_PRIVILEGE} to true will have this method use access controller to remove + * the shutdown hook with privileged permissions. + *

+ * If {@code shutdownThread} is null, no shutdown hook will be removed. + * + * @param shutdownThread The {@link Thread} that will be added as a + * {@link Runtime#addShutdownHook(Thread) shutdown hook}. + */ + @SuppressWarnings({ "deprecation", "removal" }) + public static void removeShutdownHookSafely(Thread shutdownThread) { + if (shutdownThread == null) { + return; + } + + if (ShutdownHookAccessHelperHolder.shutdownHookAccessHelper) { + java.security.AccessController.doPrivileged((java.security.PrivilegedAction) () -> { + Runtime.getRuntime().removeShutdownHook(shutdownThread); + return null; + }); + } else { + Runtime.getRuntime().removeShutdownHook(shutdownThread); + } + } + + /* + * This looks a bit strange but is needed as CoreUtils is used within Configuration code and if this was done in + * the static constructor for CoreUtils it would cause a circular dependency, potentially causing a deadlock. + * Since this is in a static holder class, it will only be loaded when CoreUtils accesses it, which won't happen + * until CoreUtils is loaded. + */ + private static final class ShutdownHookAccessHelperHolder { + private static boolean shutdownHookAccessHelper; + + static { + shutdownHookAccessHelper = Boolean + .parseBoolean(Configuration.getGlobalConfiguration().get("AZURE_ENABLE_SHUTDOWN_HOOK_WITH_PRIVILEGE")); + } + } + + static boolean isShutdownHookAccessHelper() { + return ShutdownHookAccessHelperHolder.shutdownHookAccessHelper; + } + + static void setShutdownHookAccessHelper(boolean shutdownHookAccessHelper) { + ShutdownHookAccessHelperHolder.shutdownHookAccessHelper = shutdownHookAccessHelper; + } + private ImplUtils() { } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/Configuration.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/Configuration.java index 6d7220e5df6f1..9094c37ab690c 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/Configuration.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/Configuration.java @@ -552,7 +552,7 @@ private String getLocalProperty(String name, Iterable aliases, Function< return null; } - private String getWithFallback(ConfigurationProperty property) { + private String getWithFallback(ConfigurationProperty property) { String name = property.getName(); if (!CoreUtils.isNullOrEmpty(name)) { String value = getLocalProperty(name, property.getAliases(), property.getValueSanitizer()); @@ -567,31 +567,28 @@ private String getWithFallback(ConfigurationProperty property) { } } } - return getFromEnvironment(property); + return getFromEnvironment(property.getSystemPropertyName(), property.getEnvironmentVariableName(), + property.getValueSanitizer()); } - private String getFromEnvironment(ConfigurationProperty property) { - String systemProperty = property.getSystemPropertyName(); + String getFromEnvironment(String systemProperty, String envVar, Function valueSanitizer) { if (systemProperty != null) { final String value = environmentConfiguration.getSystemProperty(systemProperty); if (value != null) { LOGGER.atVerbose() - .addKeyValue("name", property.getName()) .addKeyValue("systemProperty", systemProperty) - .addKeyValue("value", () -> property.getValueSanitizer().apply(value)) + .addKeyValue("value", () -> valueSanitizer.apply(value)) .log("Got property from system property."); return value; } } - String envVar = property.getEnvironmentVariableName(); if (envVar != null) { final String value = environmentConfiguration.getEnvironmentVariable(envVar); if (value != null) { LOGGER.atVerbose() - .addKeyValue("name", property.getName()) .addKeyValue("envVar", envVar) - .addKeyValue("value", () -> property.getValueSanitizer().apply(value)) + .addKeyValue("value", () -> valueSanitizer.apply(value)) .log("Got property from environment variable."); return value; } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/ConfigurationProperty.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/ConfigurationProperty.java index 2c62bd5a748a2..6dd50e8d91e07 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/ConfigurationProperty.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/ConfigurationProperty.java @@ -15,7 +15,7 @@ * @param Type of property value. */ public final class ConfigurationProperty { - private static final Function REDACT_VALUE_SANITIZER = (value) -> "redacted"; + static final Function REDACT_VALUE_SANITIZER = (value) -> "redacted"; private final String name; private final List aliases; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/CoreUtils.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/CoreUtils.java index 03fe46e737aae..a02213a5c12a5 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/CoreUtils.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/CoreUtils.java @@ -610,7 +610,6 @@ public static T getResultWithTimeout(Future future, Duration timeout) * @throws NullPointerException If {@code shutdownTimeout} is null. * @throws IllegalArgumentException If {@code shutdownTimeout} is zero or negative. */ - @SuppressWarnings({ "deprecation", "removal" }) public static ExecutorService addShutdownHookSafely(ExecutorService executorService, Duration shutdownTimeout) { if (executorService == null) { return null; @@ -620,8 +619,14 @@ public static ExecutorService addShutdownHookSafely(ExecutorService executorServ throw new IllegalArgumentException("'shutdownTimeout' must be a non-zero positive duration."); } + CoreUtils.addShutdownHookSafely(createExecutorServiceShutdownThread(executorService, shutdownTimeout)); + + return executorService; + } + + static Thread createExecutorServiceShutdownThread(ExecutorService executorService, Duration shutdownTimeout) { long timeoutNanos = shutdownTimeout.toNanos(); - Thread shutdownThread = new Thread(() -> { + return new Thread(() -> { try { executorService.shutdown(); if (!executorService.awaitTermination(timeoutNanos / 2, TimeUnit.NANOSECONDS)) { @@ -633,10 +638,6 @@ public static ExecutorService addShutdownHookSafely(ExecutorService executorServ executorService.shutdown(); } }); - - CoreUtils.addShutdownHookSafely(shutdownThread); - - return executorService; } /** @@ -654,22 +655,8 @@ public static ExecutorService addShutdownHookSafely(ExecutorService executorServ * {@link Runtime#addShutdownHook(Thread) shutdown hook}. * @return The {@link Thread} that was passed in. */ - @SuppressWarnings({ "deprecation", "removal" }) public static Thread addShutdownHookSafely(Thread shutdownThread) { - if (shutdownThread == null) { - return null; - } - - if (ShutdownHookAccessHelperHolder.shutdownHookAccessHelper) { - java.security.AccessController.doPrivileged((java.security.PrivilegedAction) () -> { - Runtime.getRuntime().addShutdownHook(shutdownThread); - return null; - }); - } else { - Runtime.getRuntime().addShutdownHook(shutdownThread); - } - - return shutdownThread; + return ImplUtils.addShutdownHookSafely(shutdownThread); } /** @@ -800,27 +787,4 @@ public static OffsetDateTime parseBestOffsetDateTime(String dateString) { return OffsetDateTime.from(temporal); } } - - /* - * This looks a bit strange but is needed as CoreUtils is used within Configuration code and if this was done in - * the static constructor for CoreUtils it would cause a circular dependency, potentially causing a deadlock. - * Since this is in a static holder class, it will only be loaded when CoreUtils accesses it, which won't happen - * until CoreUtils is loaded. - */ - private static final class ShutdownHookAccessHelperHolder { - private static boolean shutdownHookAccessHelper; - - static { - shutdownHookAccessHelper = Boolean - .parseBoolean(Configuration.getGlobalConfiguration().get("AZURE_ENABLE_SHUTDOWN_HOOK_WITH_PRIVILEGE")); - } - } - - static boolean isShutdownHookAccessHelper() { - return ShutdownHookAccessHelperHolder.shutdownHookAccessHelper; - } - - static void setShutdownHookAccessHelper(boolean shutdownHookAccessHelper) { - ShutdownHookAccessHelperHolder.shutdownHookAccessHelper = shutdownHookAccessHelper; - } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/SharedExecutorService.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/SharedExecutorService.java new file mode 100644 index 0000000000000..d4de3ab0a49a7 --- /dev/null +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/SharedExecutorService.java @@ -0,0 +1,373 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.core.util; + +import com.azure.core.implementation.ReflectionUtils; +import com.azure.core.implementation.ReflectiveInvoker; +import com.azure.core.util.logging.ClientLogger; + +import java.time.Duration; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Function; + +/** + * An {@link ExecutorService} that is shared by multiple consumers. + *

+ * The shared executor service is created using the following configuration settings: + *

    + *
  • {@code azure.sdk.shared.threadpool.maxpoolsize} system property or + * {@code AZURE_SDK_SHARED_THREADPOOL_MAXPOOLSIZE} environment variable - The maximum pool size of the shared + * executor service. If not set, it defaults to 10 times the number of available processors.
  • + *
  • {@code azure.sdk.shared.threadpool.keepalivemillis} system property or + * {code AZURE_SDK_SHARED_THREADPOOL_KEEPALIVEMILLIS} environment variable - The keep alive time in millis for + * threads in the shared executor service. If not set, it defaults to 60 seconds. Limited to integer size.
  • + *
  • {@code azure.sdk.shared.threadpool.usevirtualthreads} system property or + * {@code AZURE_SDK_SHARED_THREADPOOL_USEVIRTUALTHREADS} environment variable - A boolean flag to indicate if the + * shared executor service should use virtual threads. If not set, it defaults to true. Ignored if virtual threads + * are not available in the runtime.
  • + *
+ */ +@SuppressWarnings({ "resource", "NullableProblems" }) +public final class SharedExecutorService implements ExecutorService { + private static final ClientLogger LOGGER = new ClientLogger(SharedExecutorService.class); + + // Shared thread counter for all instances of SharedExecutorService created using the empty factory method. + private static final AtomicLong AZURE_SDK_THREAD_COUNTER = new AtomicLong(); + private static final String AZURE_SDK_THREAD_NAME = "azure-sdk-global-thread-"; + + // The thread pool size for the shared executor service. + private static final int THREAD_POOL_SIZE; + + // The thread pool keep alive time for the shared executor service. + private static final int THREAD_POOL_KEEP_ALIVE_MILLIS; + + // Virtual thread support for the shared executor service. + private static final boolean THREAD_POOL_VIRTUAL; + + private static final SharedExecutorService INSTANCE; + + static { + THREAD_POOL_SIZE + = getConfig("azure.sdk.shared.threadpool.maxpoolsize", "AZURE_SDK_SHARED_THREADPOOL_MAXPOOLSIZE", + Integer::parseInt, 10 * Runtime.getRuntime().availableProcessors()); + + THREAD_POOL_KEEP_ALIVE_MILLIS = getConfig("azure.sdk.shared.threadpool.keepalivemillis", + "AZURE_SDK_SHARED_THREADPOOL_KEEPALIVEMILLIS", Integer::parseInt, 60_000); + + THREAD_POOL_VIRTUAL = getConfig("azure.sdk.shared.threadpool.usevirtualthreads", + "AZURE_SDK_SHARED_THREADPOOL_USEVIRTUALTHREADS", Boolean::parseBoolean, true); + + INSTANCE = new SharedExecutorService(); + } + + private static T getConfig(String systemProperty, String envVar, Function converter, + T defaultValue) { + String foundValue = Configuration.getGlobalConfiguration() + .getFromEnvironment(systemProperty, envVar, ConfigurationProperty.REDACT_VALUE_SANITIZER); + if (foundValue == null) { + LOGGER.atVerbose() + .addKeyValue("systemProperty", systemProperty) + .addKeyValue("envVar", envVar) + .addKeyValue("defaultValue", defaultValue) + .log("Configuration value not found, using default."); + return defaultValue; + } + + try { + T returnValue = converter.apply(foundValue); + LOGGER.atVerbose() + .addKeyValue("systemProperty", systemProperty) + .addKeyValue("envVar", envVar) + .addKeyValue("value", foundValue) + .log("Found configuration value."); + return returnValue; + } catch (RuntimeException e) { + LOGGER.atVerbose() + .addKeyValue("systemProperty", systemProperty) + .addKeyValue("envVar", envVar) + .addKeyValue("value", foundValue) + .addKeyValue("defaultValue", defaultValue) + .log("Failed to convert found configuration value, using default."); + return defaultValue; + } + } + + private static final boolean VIRTUAL_THREAD_SUPPORTED; + private static final ReflectiveInvoker GET_VIRTUAL_THREAD_BUILDER; + private static final ReflectiveInvoker SET_VIRTUAL_THREAD_BUILDER_THREAD_NAME; + private static final ReflectiveInvoker CREATE_VIRTUAL_THREAD_FACTORY; + + static { + boolean virtualThreadSupported; + ReflectiveInvoker getVirtualThreadBuilder; + ReflectiveInvoker setVirtualThreadBuilderThreadName; + ReflectiveInvoker createVirtualThreadFactory; + + try { + getVirtualThreadBuilder = ReflectionUtils.getMethodInvoker(null, + Class.forName("java.lang.Thread").getDeclaredMethod("ofVirtual")); + setVirtualThreadBuilderThreadName = ReflectionUtils.getMethodInvoker(null, + Class.forName("java.lang.Thread$Builder").getDeclaredMethod("name", String.class)); + createVirtualThreadFactory = ReflectionUtils.getMethodInvoker(null, + Class.forName("java.lang.Thread$Builder").getDeclaredMethod("factory")); + virtualThreadSupported = true; + LOGGER.verbose("Virtual threads are supported in the current runtime."); + } catch (Exception | LinkageError e) { + LOGGER.atVerbose() + .addKeyValue("runtime", System.getProperty("java.version")) + .log("Virtual threads are not supported in the current runtime.", e); + virtualThreadSupported = false; + getVirtualThreadBuilder = null; + setVirtualThreadBuilderThreadName = null; + createVirtualThreadFactory = null; + } + + VIRTUAL_THREAD_SUPPORTED = virtualThreadSupported; + GET_VIRTUAL_THREAD_BUILDER = getVirtualThreadBuilder; + SET_VIRTUAL_THREAD_BUILDER_THREAD_NAME = setVirtualThreadBuilderThreadName; + CREATE_VIRTUAL_THREAD_FACTORY = createVirtualThreadFactory; + } + + private final ExecutorService executorService; + + private SharedExecutorService() { + this.executorService = createSharedExecutor(); + } + + /** + * Gets the shared instance of the executor service. + * + * @return The shared instance of the executor service. + */ + public static SharedExecutorService getInstance() { + return INSTANCE; + } + + // /** + // * Sets the backing executor service for the shared instance. + // *

+ // * This updates the executor service for all users of the {@link #getInstance() shared instance}. Meaning, if + // * another area in code already had a reference to the shared instance, it will now use the passed executor service + // * to execute tasks. + // *

+ // * If the executor service is already set, this will replace it with the new executor service. If the replaced + // * executor service was created by this class, it will be shut down. + // *

+ // * If the passed executor service is null, this will throw a {@link NullPointerException}. If the passed executor + // * + // * @param executorService The executor service to set as the shared instance. + // * @throws NullPointerException If the passed executor service is null. + // * @throws IllegalStateException If the passed executor service is shutdown or terminated. + // */ + // public static void setExecutorService(ExecutorService executorService) { + // // We allow for the global executor service to be set from an external source to allow for consumers of the SDK + // // to use their own thread management to run Azure SDK tasks. This allows for the SDKs to perform deeper + // // integration into an environment, such as the consumer environment knowing details about capacity, allowing + // // the custom executor service to better manage resources than our more general 10x the number of processors. + // // Another scenario could be an executor service that creates threads with specific permissions, such as + // // allowing Azure Core or Jackson to perform deep reflection on classes that are not normally allowed. + // Objects.requireNonNull(executorService, "'executorService' cannot be null."); + // if (executorService.isShutdown() || executorService.isTerminated()) { + // throw new IllegalStateException("The passed executor service is shutdown or terminated."); + // } + // + // ExecutorWithMetadata existing + // = INSTANCE.wrappedExecutorService.getAndSet(new ExecutorWithMetadata(executorService, null)); + // + // if (existing != null) { + // // This is calling ExecutorWithMetadata.shutdown() which will shutdown the executor service if it was + // // created by this class. Otherwise, it's a no-op. + // existing.shutdown(); + // } + // } + + /** + * Shutdown isn't supported for this executor service as it is shared by multiple consumers. + *

+ * Calling this method will result in an {@link UnsupportedOperationException} being thrown. + * + * @throws UnsupportedOperationException This method will always throw an exception. + */ + @Override + public void shutdown() { + // This doesn't do anything as this is meant to be shared and shouldn't be shut down by one consumer. + throw LOGGER.logThrowableAsError( + new UnsupportedOperationException("This executor service is shared and cannot be shut down.")); + } + + /** + * Shutdown isn't supported for this executor service as it is shared by multiple consumers. + *

+ * Calling this method will result in an {@link UnsupportedOperationException} being thrown. + * + * @return Nothing will be returned as an exception will always be thrown. + * @throws UnsupportedOperationException This method will always throw an exception. + */ + @Override + public List shutdownNow() { + throw LOGGER.logThrowableAsError( + new UnsupportedOperationException("This executor service is shared and cannot be shut down.")); + } + + /** + * Checks if the executor service is shutdown. + *

+ * Will always return false as the shared executor service cannot be shut down. + * + * @return False, as the shared executor service cannot be shut down. + */ + @Override + public boolean isShutdown() { + return false; + } + + /** + * Checks if the executor service is terminated. + *

+ * Will always return false as the shared executor service cannot be terminated. + * + * @return False, as the shared executor service cannot be terminated. + */ + @Override + public boolean isTerminated() { + return false; + } + + /** + * Shutdown isn't supported for this executor service as it is shared by multiple consumers. + *

+ * Calling this method will result in an {@link UnsupportedOperationException} being thrown. + * + * @param timeout The amount of time to wait for the executor service to shutdown. + * @param unit The unit of time for the timeout. + * @return Nothing will be returned as an exception will always be thrown. + * @throws UnsupportedOperationException This method will always throw an exception. + */ + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + throw LOGGER.logThrowableAsError( + new UnsupportedOperationException("This executor service is shared and cannot be terminated.")); + } + + @Override + public void execute(Runnable command) { + ensureNotShutdown().execute(command); + } + + @Override + public Future submit(Callable task) { + return ensureNotShutdown().submit(task); + } + + @Override + public Future submit(Runnable task, T result) { + return ensureNotShutdown().submit(task, result); + } + + @Override + public Future submit(Runnable task) { + return ensureNotShutdown().submit(task); + } + + @Override + public List> invokeAll(Collection> tasks) throws InterruptedException { + return ensureNotShutdown().invokeAll(tasks); + } + + @Override + public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) + throws InterruptedException { + return ensureNotShutdown().invokeAll(tasks, timeout, unit); + } + + @Override + public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { + return ensureNotShutdown().invokeAny(tasks); + } + + @Override + public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + return ensureNotShutdown().invokeAny(tasks, timeout, unit); + } + + private ExecutorService ensureNotShutdown() { + return executorService; + // return wrappedExecutorService.updateAndGet(wrapper -> { + // if (wrapper == null || wrapper.executorService.isShutdown() || wrapper.executorService.isTerminated()) { + // return createSharedExecutor(); + // } else { + // return wrapper; + // } + // }).executorService; + } + + private static ExecutorService createSharedExecutor() { + ThreadFactory threadFactory; + if (VIRTUAL_THREAD_SUPPORTED && THREAD_POOL_VIRTUAL) { + try { + LOGGER.verbose("Attempting to create a virtual thread factory."); + threadFactory = createVirtualThreadFactory(); + LOGGER.verbose("Successfully created a virtual thread factory."); + } catch (Exception e) { + LOGGER.info("Failed to create a virtual thread factory, falling back to non-virtual threads.", e); + threadFactory = createNonVirtualThreadFactory(); + } + } else { + threadFactory = createNonVirtualThreadFactory(); + } + + ExecutorService executorService = new ThreadPoolExecutor(0, THREAD_POOL_SIZE, THREAD_POOL_KEEP_ALIVE_MILLIS, + TimeUnit.MILLISECONDS, new SynchronousQueue<>(), threadFactory); + Thread shutdownThread = CoreUtils.createExecutorServiceShutdownThread(executorService, Duration.ofSeconds(5)); + CoreUtils.addShutdownHookSafely(shutdownThread); + + return executorService; + } + + private static ThreadFactory createVirtualThreadFactory() throws Exception { + Object virtualThreadBuilder = GET_VIRTUAL_THREAD_BUILDER.invokeStatic(); + SET_VIRTUAL_THREAD_BUILDER_THREAD_NAME.invokeWithArguments(virtualThreadBuilder, AZURE_SDK_THREAD_NAME); + return (ThreadFactory) CREATE_VIRTUAL_THREAD_FACTORY.invokeWithArguments(virtualThreadBuilder); + } + + private static ThreadFactory createNonVirtualThreadFactory() { + return r -> { + Thread thread = new Thread(r, AZURE_SDK_THREAD_NAME + AZURE_SDK_THREAD_COUNTER.getAndIncrement()); + thread.setDaemon(true); + + return thread; + }; + } + + // private static final class ExecutorWithMetadata { + // private final Thread shutdownThread; + // private final ExecutorService executorService; + // + // ExecutorWithMetadata(ExecutorService executorService, Thread shutdownThread) { + // this.executorService = executorService; + // this.shutdownThread = shutdownThread; + // } + // + // void shutdown() { + // // The executor service is only shutdown if there is a shutdown thread as that indicates the executor + // // service was created by this class. + // if (shutdownThread != null) { + // executorService.shutdown(); + // ImplUtils.removeShutdownHookSafely(shutdownThread); + // } + // } + // } +} diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollingUtil.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollingUtil.java index 17b5d312f2122..9e85613dd6621 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollingUtil.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollingUtil.java @@ -7,6 +7,7 @@ import com.azure.core.http.HttpHeaderName; import com.azure.core.http.rest.Response; import com.azure.core.implementation.ImplUtils; +import com.azure.core.util.SharedExecutorService; import com.azure.core.util.logging.ClientLogger; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -15,10 +16,7 @@ import java.time.Duration; import java.util.Objects; import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiFunction; import java.util.function.Function; @@ -40,49 +38,47 @@ static PollResponse pollingLoop(PollingContext pollingContext, Duratio PollResponse intermediatePollResponse = pollingContext.getLatestResponse(); boolean firstPoll = true; - final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); - try { - while (!intermediatePollResponse.getStatus().isComplete()) { - long elapsedTime = System.currentTimeMillis() - startTime; - if (timeBound && elapsedTime >= timeoutInMillis) { - if (intermediatePollResponse.getStatus().equals(statusToWaitFor) || isWaitForStatus) { - return intermediatePollResponse; - } else { - throw LOGGER.logExceptionAsError(new RuntimeException( - new TimeoutException("Polling didn't complete before the timeout period."))); - } - } - - if (intermediatePollResponse.getStatus().equals(statusToWaitFor)) { + while (!intermediatePollResponse.getStatus().isComplete()) { + long elapsedTime = System.currentTimeMillis() - startTime; + if (timeBound && elapsedTime >= timeoutInMillis) { + if (intermediatePollResponse.getStatus().equals(statusToWaitFor) || isWaitForStatus) { return intermediatePollResponse; - } - - final Future> pollOp; - if (firstPoll) { - firstPoll = false; - pollOp = scheduler.submit(() -> pollOperation.apply(pollingContext)); } else { - pollOp = scheduler.schedule(() -> pollOperation.apply(pollingContext), - getDelay(intermediatePollResponse, pollInterval).toMillis(), TimeUnit.MILLISECONDS); + throw LOGGER.logExceptionAsError(new RuntimeException( + new TimeoutException("Polling didn't complete before the timeout period."))); } + } - try { - long pollTimeout = timeBound ? timeoutInMillis - elapsedTime : -1; - intermediatePollResponse = ImplUtils.getResultWithTimeout(pollOp, pollTimeout); - pollingContext.setLatestResponse(intermediatePollResponse); - } catch (InterruptedException | ExecutionException | TimeoutException e) { - // waitUntil should not throw when timeout is reached. - if (isWaitForStatus) { - return intermediatePollResponse; - } - throw LOGGER.logExceptionAsError(new RuntimeException(e)); - } + if (intermediatePollResponse.getStatus().equals(statusToWaitFor)) { + return intermediatePollResponse; } - return intermediatePollResponse; - } finally { - scheduler.shutdown(); + final Future> pollOp; + if (firstPoll) { + firstPoll = false; + pollOp = SharedExecutorService.getInstance().submit(() -> pollOperation.apply(pollingContext)); + } else { + final PollResponse finalIntermediatePollResponse = intermediatePollResponse; + pollOp = SharedExecutorService.getInstance().submit(() -> { + Thread.sleep(getDelay(finalIntermediatePollResponse, pollInterval).toMillis()); + return pollOperation.apply(pollingContext); + }); + } + + try { + long pollTimeout = timeBound ? timeoutInMillis - elapsedTime : -1; + intermediatePollResponse = ImplUtils.getResultWithTimeout(pollOp, pollTimeout); + pollingContext.setLatestResponse(intermediatePollResponse); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + // waitUntil should not throw when timeout is reached. + if (isWaitForStatus) { + return intermediatePollResponse; + } + throw LOGGER.logExceptionAsError(new RuntimeException(e)); + } } + + return intermediatePollResponse; } static Flux> pollingLoopAsync(PollingContext pollingContext, diff --git a/sdk/core/azure-core/src/test/java/com/azure/core/util/CoreUtilsSecurityIT.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/ImplUtilsSecurityIT.java similarity index 89% rename from sdk/core/azure-core/src/test/java/com/azure/core/util/CoreUtilsSecurityIT.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/ImplUtilsSecurityIT.java index 1391b14359905..5ffc09d03b104 100644 --- a/sdk/core/azure-core/src/test/java/com/azure/core/util/CoreUtilsSecurityIT.java +++ b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/ImplUtilsSecurityIT.java @@ -1,7 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.core.util; +package com.azure.core.implementation; +import com.azure.core.util.CoreUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @@ -16,12 +17,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows; /** - * Tests {@link CoreUtils} functionality when there is a SecurityManager. + * Tests {@link ImplUtils} functionality when there is a SecurityManager. */ @SuppressWarnings("removal") @Execution(ExecutionMode.SAME_THREAD) @Isolated("Mutates the global SecurityManager") -public class CoreUtilsSecurityIT { +public class ImplUtilsSecurityIT { private static final Duration SHUTDOWN_TIMEOUT = Duration.ofSeconds(5); private boolean originalShutdownHookAccessHelper; @@ -29,7 +30,7 @@ public class CoreUtilsSecurityIT { private java.security.Policy originalPolicy; public void captureDefaultConfigurations() { - originalShutdownHookAccessHelper = CoreUtils.isShutdownHookAccessHelper(); + originalShutdownHookAccessHelper = ImplUtils.isShutdownHookAccessHelper(); originalManager = java.lang.System.getSecurityManager(); originalPolicy = java.security.Policy.getPolicy(); @@ -40,7 +41,7 @@ public void captureDefaultConfigurations() { } public void revertDefaultConfigurations() { - CoreUtils.setShutdownHookAccessHelper(originalShutdownHookAccessHelper); + ImplUtils.setShutdownHookAccessHelper(originalShutdownHookAccessHelper); java.lang.System.setSecurityManager(originalManager); java.security.Policy.setPolicy(originalPolicy); @@ -75,7 +76,7 @@ public void securityAndAccessHelperNotMatchingPreventsSerialization() throws Exc captureDefaultConfigurations(); try { - CoreUtils.setShutdownHookAccessHelper(true); + ImplUtils.setShutdownHookAccessHelper(true); java.security.Policy .setPolicy(java.security.Policy.getInstance("JavaPolicy", getUriParameter("basic-permissions.policy"))); @@ -96,7 +97,7 @@ public void securityAndAccessHelperWorks() throws Exception { captureDefaultConfigurations(); try { - CoreUtils.setShutdownHookAccessHelper(true); + ImplUtils.setShutdownHookAccessHelper(true); java.security.Policy.setPolicy( java.security.Policy.getInstance("JavaPolicy", getUriParameter("access-helper-succeeds.policy"))); @@ -117,7 +118,7 @@ public void noSecurityRestrictionsWorks() { captureDefaultConfigurations(); try { - CoreUtils.setShutdownHookAccessHelper(false); + ImplUtils.setShutdownHookAccessHelper(false); assertDoesNotThrow( () -> CoreUtils.addShutdownHookSafely(Executors.newCachedThreadPool(), SHUTDOWN_TIMEOUT)); @@ -128,6 +129,6 @@ public void noSecurityRestrictionsWorks() { private static URIParameter getUriParameter(String policyFile) throws URISyntaxException { return new URIParameter( - CoreUtilsSecurityIT.class.getResource("/CoreUtilsSecurityPolicies/" + policyFile).toURI()); + ImplUtilsSecurityIT.class.getResource("/CoreUtilsSecurityPolicies/" + policyFile).toURI()); } } diff --git a/sdk/cosmos/azure-cosmos-benchmark/pom.xml b/sdk/cosmos/azure-cosmos-benchmark/pom.xml index cb75cc9340972..7b600be0aaa62 100644 --- a/sdk/cosmos/azure-cosmos-benchmark/pom.xml +++ b/sdk/cosmos/azure-cosmos-benchmark/pom.xml @@ -51,19 +51,19 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.59.0 + 4.60.0-beta.1 com.azure azure-cosmos-encryption - 2.11.0 + 2.12.0-beta.1 com.azure azure-identity - 1.12.0 + 1.12.1 com.azure @@ -182,7 +182,7 @@ Licensed under the MIT License. com.azure azure-security-keyvault-keys - 4.8.2 + 4.8.3 compile diff --git a/sdk/cosmos/azure-cosmos-dotnet-benchmark/pom.xml b/sdk/cosmos/azure-cosmos-dotnet-benchmark/pom.xml index 368eac3abb502..dcb27b69c9df8 100644 --- a/sdk/cosmos/azure-cosmos-dotnet-benchmark/pom.xml +++ b/sdk/cosmos/azure-cosmos-dotnet-benchmark/pom.xml @@ -50,7 +50,7 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.59.0 + 4.60.0-beta.1 diff --git a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md index 141dd41f687cc..af54e665c3d93 100644 --- a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md @@ -1,5 +1,15 @@ ## Release History +### 2.12.0-beta.1 (Unreleased) + +#### Features Added + +#### Breaking Changes + +#### Bugs Fixed + +#### Other Changes + ### 2.11.0 (2024-04-27) #### Other Changes * Updated `azure-cosmos` to version `4.59.0`. diff --git a/sdk/cosmos/azure-cosmos-encryption/pom.xml b/sdk/cosmos/azure-cosmos-encryption/pom.xml index cd557b9073f01..1d853540d2692 100644 --- a/sdk/cosmos/azure-cosmos-encryption/pom.xml +++ b/sdk/cosmos/azure-cosmos-encryption/pom.xml @@ -13,7 +13,7 @@ Licensed under the MIT License. com.azure azure-cosmos-encryption - 2.11.0 + 2.12.0-beta.1 Encryption Plugin for Azure Cosmos DB SDK This Package contains Encryption Plugin for Microsoft Azure Cosmos SDK jar @@ -57,13 +57,13 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.59.0 + 4.60.0-beta.1 com.azure azure-security-keyvault-keys - 4.8.2 + 4.8.3 test @@ -80,7 +80,7 @@ Licensed under the MIT License. com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/CHANGELOG.md b/sdk/cosmos/azure-cosmos-kafka-connect/CHANGELOG.md index c810485f956f7..9f80312c76e87 100644 --- a/sdk/cosmos/azure-cosmos-kafka-connect/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-kafka-connect/CHANGELOG.md @@ -1,6 +1,6 @@ ## Release History -### 1.0.0-beta.2 (Unreleased) +### 1.0.0-beta.3 (Unreleased) #### Features Added @@ -10,6 +10,11 @@ #### Other Changes +### 1.0.0-beta.2 (2024-05-01) + +#### Other Changes +* Added support to create metadata container if not exists when using `Cosmos` as the metadata storage type and using `MasterKey` auth - See [PR 39973](https://github.com/Azure/azure-sdk-for-java/pull/39973) + ### 1.0.0-beta.1 (2024-04-26) #### Features Added diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/doc/configuration-reference.md b/sdk/cosmos/azure-cosmos-kafka-connect/doc/configuration-reference.md index a326f75be4ac8..9e5b224b60a12 100644 --- a/sdk/cosmos/azure-cosmos-kafka-connect/doc/configuration-reference.md +++ b/sdk/cosmos/azure-cosmos-kafka-connect/doc/configuration-reference.md @@ -2,65 +2,65 @@ ## Generic Configuration -| Config Property Name | Default | Description | -|:--------------------------------------------------------------------|:-----------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `azure.cosmos.account.endpoint` | None | Cosmos DB Account Endpoint Uri | -| `azure.cosmos.account.environment` | `Azure` | The azure environment of the CosmosDB account: `Azure`, `AzureChina`, `AzureUsGovernment`, `AzureGermany`. | -| `azure.cosmos.account.tenantId` | `""` | The tenantId of the CosmosDB account. Required for `ServicePrincipal` authentication. | -| `azure.cosmos.auth.type` | `MasterKey` | There are two auth types are supported currently: `MasterKey`(PrimaryReadWriteKeys, SecondReadWriteKeys, PrimaryReadOnlyKeys, SecondReadWriteKeys), `ServicePrincipal` | -| `azure.cosmos.account.key` | `""` | Cosmos DB Account Key (only required in case of `auth.type` as `MasterKey`) | -| `azure.cosmos.auth.aad.clientId` | `""` | The clientId/ApplicationId of the service principal. Required for `ServicePrincipal` authentication. | -| `azure.cosmos.auth.aad.clientSecret` | `""` | The client secret/password of the service principal. | -| `azure.cosmos.mode.gateway` | `false` | Flag to indicate whether to use gateway mode. By default it is false, means SDK uses direct mode. https://learn.microsoft.com/azure/cosmos-db/nosql/sdk-connection-modes | -| `azure.cosmos.preferredRegionList` | `[]` | Preferred regions list to be used for a multi region Cosmos DB account. This is a comma separated value (e.g., `[East US, West US]` or `East US, West US`) provided preferred regions will be used as hint. You should use a collocated kafka cluster with your Cosmos DB account and pass the kafka cluster region as preferred region. See list of azure regions [here](https://docs.microsoft.com/dotnet/api/microsoft.azure.documents.locationnames?view=azure-dotnet&preserve-view=true). | -| `azure.cosmos.application.name` | `""` | Application name. Will be added as the userAgent suffix. | -| `azure.cosmos.throughputControl.enabled` | `false` | A flag to indicate whether throughput control is enabled. | -| `azure.cosmos.throughputControl.account.endpoint` | `""` | Cosmos DB Throughput Control Account Endpoint Uri. | -| `azure.cosmos.throughputControl.account.environment` | `Azure` | The azure environment of the CosmosDB account: `Azure`, `AzureChina`, `AzureUsGovernment`, `AzureGermany`. | -| `azure.cosmos.throughputControl.account.tenantId` | `""` | The tenantId of the CosmosDB account. Required for `ServicePrincipal` authentication. | -| `azure.cosmos.throughputControl.auth.type` | `MasterKey` | There are two auth types are supported currently: `MasterKey`(PrimaryReadWriteKeys, SecondReadWriteKeys, PrimaryReadOnlyKeys, SecondReadWriteKeys), `ServicePrincipal` | -| `azure.cosmos.throughputControl.account.key` | `""` | Cosmos DB Throughput Control Account Key (only required in case of `throughputControl.auth.type` as `MasterKey`). | -| `azure.cosmos.throughputControl.auth.aad.clientId` | `""` | The clientId/ApplicationId of the service principal. Required for `ServicePrincipal` authentication. | -| `azure.cosmos.throughputControl.auth.aad.clientSecret` | `""` | The client secret/password of the service principal. | -| `azure.cosmos.throughputControl.preferredRegionList` | `[]` | Preferred regions list to be used for a multi region Cosmos DB account. This is a comma separated value (e.g., `[East US, West US]` or `East US, West US`) provided preferred regions will be used as hint. You should use a collocated kafka cluster with your Cosmos DB account and pass the kafka cluster region as preferred region. See list of azure regions [here](https://docs.microsoft.com/dotnet/api/microsoft.azure.documents.locationnames?view=azure-dotnet&preserve-view=true). | -| `azure.cosmos.throughputControl.mode.gateway` | `false` | Flag to indicate whether to use gateway mode. By default it is false, means SDK uses direct mode. https://learn.microsoft.com/azure/cosmos-db/nosql/sdk-connection-modes | -| `azure.cosmos.throughputControl.group.name` | `""` | Throughput control group name. Since customer is allowed to create many groups for a container, the name should be unique. | -| `azure.cosmos.throughputControl.targetThroughput` | `-1` | Throughput control group target throughput. The value should be larger than 0. | -| `azure.cosmos.throughputControl.targetThroughputThreshold` | `-1` | Throughput control group target throughput threshold. The value should be between (0,1]. | -| `azure.cosmos.throughputControl.priorityLevel` | `None` | Throughput control group priority level. The value can be None, High or Low. | -| `azure.cosmos.throughputControl.globalControl.database.name` | `""` | Database which will be used for throughput global control. | -| `azure.cosmos.throughputControl.globalControl.container.name` | `""` | Container which will be used for throughput global control. | -| `azure.cosmos.throughputControl.globalControl.renewIntervalInMS` | `-1` | This controls how often the client is going to update the throughput usage of itself and adjust its own throughput share based on the throughput usage of other clients. Default is 5s, the allowed min value is 5s. | -| `azure.cosmos.throughputControl.globalControl.expireIntervalInMS` | `-1` | This controls how quickly we will detect the client has been offline and hence allow its throughput share to be taken by other clients. Default is 11s, the allowed min value is 2 * renewIntervalInMS + 1. | +| Config Property Name | Default | Description | +|:------------------------------------------------------------------|:-----------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `azure.cosmos.account.endpoint` | None | Cosmos DB Account Endpoint Uri | +| `azure.cosmos.account.environment` | `Azure` | The azure environment of the CosmosDB account: `Azure`, `AzureChina`, `AzureUsGovernment`, `AzureGermany`. | +| `azure.cosmos.account.tenantId` | `""` | The tenantId of the CosmosDB account. Required for `ServicePrincipal` authentication. | +| `azure.cosmos.auth.type` | `MasterKey` | There are two auth types are supported currently: `MasterKey`(PrimaryReadWriteKeys, SecondReadWriteKeys, PrimaryReadOnlyKeys, SecondReadWriteKeys), `ServicePrincipal` | +| `azure.cosmos.account.key` | `""` | Cosmos DB Account Key (only required in case of `auth.type` as `MasterKey`) | +| `azure.cosmos.auth.aad.clientId` | `""` | The clientId/ApplicationId of the service principal. Required for `ServicePrincipal` authentication. | +| `azure.cosmos.auth.aad.clientSecret` | `""` | The client secret/password of the service principal. | +| `azure.cosmos.mode.gateway` | `false` | Flag to indicate whether to use gateway mode. By default it is false, means SDK uses direct mode. https://learn.microsoft.com/azure/cosmos-db/nosql/sdk-connection-modes | +| `azure.cosmos.preferredRegionList` | `[]` | Preferred regions list to be used for a multi region Cosmos DB account. This is a comma separated value (e.g., `[East US, West US]` or `East US, West US`) provided preferred regions will be used as hint. You should use a collocated kafka cluster with your Cosmos DB account and pass the kafka cluster region as preferred region. See list of azure regions [here](https://docs.microsoft.com/dotnet/api/microsoft.azure.documents.locationnames?view=azure-dotnet&preserve-view=true). | +| `azure.cosmos.application.name` | `""` | Application name. Will be added as the userAgent suffix. | +| `azure.cosmos.throughputControl.enabled` | `false` | A flag to indicate whether throughput control is enabled. | +| `azure.cosmos.throughputControl.account.endpoint` | `""` | Cosmos DB Throughput Control Account Endpoint Uri. | +| `azure.cosmos.throughputControl.account.environment` | `Azure` | The azure environment of the CosmosDB account: `Azure`, `AzureChina`, `AzureUsGovernment`, `AzureGermany`. | +| `azure.cosmos.throughputControl.account.tenantId` | `""` | The tenantId of the CosmosDB account. Required for `ServicePrincipal` authentication. | +| `azure.cosmos.throughputControl.auth.type` | `MasterKey` | There are two auth types are supported currently: `MasterKey`(PrimaryReadWriteKeys, SecondReadWriteKeys, PrimaryReadOnlyKeys, SecondReadWriteKeys), `ServicePrincipal` | +| `azure.cosmos.throughputControl.account.key` | `""` | Cosmos DB Throughput Control Account Key (only required in case of `throughputControl.auth.type` as `MasterKey`). | +| `azure.cosmos.throughputControl.auth.aad.clientId` | `""` | The clientId/ApplicationId of the service principal. Required for `ServicePrincipal` authentication. | +| `azure.cosmos.throughputControl.auth.aad.clientSecret` | `""` | The client secret/password of the service principal. | +| `azure.cosmos.throughputControl.preferredRegionList` | `[]` | Preferred regions list to be used for a multi region Cosmos DB account. This is a comma separated value (e.g., `[East US, West US]` or `East US, West US`) provided preferred regions will be used as hint. You should use a collocated kafka cluster with your Cosmos DB account and pass the kafka cluster region as preferred region. See list of azure regions [here](https://docs.microsoft.com/dotnet/api/microsoft.azure.documents.locationnames?view=azure-dotnet&preserve-view=true). | +| `azure.cosmos.throughputControl.mode.gateway` | `false` | Flag to indicate whether to use gateway mode. By default it is false, means SDK uses direct mode. https://learn.microsoft.com/azure/cosmos-db/nosql/sdk-connection-modes | +| `azure.cosmos.throughputControl.group.name` | `""` | Throughput control group name. Since customer is allowed to create many groups for a container, the name should be unique. | +| `azure.cosmos.throughputControl.targetThroughput` | `-1` | Throughput control group target throughput. The value should be larger than 0. | +| `azure.cosmos.throughputControl.targetThroughputThreshold` | `-1` | Throughput control group target throughput threshold. The value should be between (0,1]. | +| `azure.cosmos.throughputControl.priorityLevel` | `None` | Throughput control group priority level. The value can be None, High or Low. | +| `azure.cosmos.throughputControl.globalControl.database.name` | `""` | Database which will be used for throughput global control. | +| `azure.cosmos.throughputControl.globalControl.container.name` | `""` | Container which will be used for throughput global control. | +| `azure.cosmos.throughputControl.globalControl.renewIntervalInMS` | `-1` | This controls how often the client is going to update the throughput usage of itself and adjust its own throughput share based on the throughput usage of other clients. Default is 5s, the allowed min value is 5s. | +| `azure.cosmos.throughputControl.globalControl.expireIntervalInMS` | `-1` | This controls how quickly we will detect the client has been offline and hence allow its throughput share to be taken by other clients. Default is 11s, the allowed min value is 2 * renewIntervalInMS + 1. | ## Source Connector Configuration -| Config Property Name | Default | Description | -|:--------------------------------------------------|:---------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `azure.cosmos.source.database.name` | None | Cosmos DB database name. | -| `azure.cosmos.source.containers.includeAll` | `false` | Flag to indicate whether reading from all containers. | -| `azure.cosmos.source.containers.includedList` | `[]` | Containers included. This config will be ignored if azure.cosmos.source.containers.includeAll is true. | -| `azure.cosmos.source.containers.topicMap` | `[]` | A comma delimited list of Kafka topics mapped to Cosmos containers. For example: topic1#con1,topic2#con2. By default, container name is used as the name of the kafka topic to publish data to, can use this property to override the default config | -| `azure.cosmos.source.changeFeed.startFrom` | `Beginning` | ChangeFeed Start from settings (Now, Beginning or a certain point in time (UTC) for example 2020-02-10T14:15:03) - the default value is 'Beginning'. | -| `azure.cosmos.source.changeFeed.mode` | `LatestVersion` | ChangeFeed mode (LatestVersion or AllVersionsAndDeletes). | -| `azure.cosmos.source.changeFeed.maxItemCountHint` | `1000` | The maximum number of documents returned in a single change feed request. But the number of items received might be higher than the specified value if multiple items are changed by the same transaction. | -| `azure.cosmos.source.metadata.poll.delay.ms` | `300000` | Indicates how often to check the metadata changes (including container split/merge, adding/removing/recreated containers). When changes are detected, it will reconfigure the tasks. Default is 5 minutes. | -| `azure.cosmos.source.metadata.storage.type` | `Kafka` | The storage type of the metadata. Two types are supported: Cosmos, Kafka. | -| `azure.cosmos.source.metadata.storage.name` | `_cosmos.metadata.topic` | The resource name of the metadata storage. If metadata storage type is Kafka topic, then this config refers to kafka topic name, the metadata topic will be created if it does not already exist, else it will use the pre-created topic. If metadata storage type is CosmosDB container, then this config refers to container name, please pre-create the metadata container partitioned by /id. | -| `azure.cosmos.source.messageKey.enabled` | `true` | Whether to set the kafka record message key. | -| `azure.cosmos.source.messageKey.field` | `id` | The field to use as the message key. | +| Config Property Name | Default | Description | +|:--------------------------------------------------|:-------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `azure.cosmos.source.database.name` | None | Cosmos DB database name. | +| `azure.cosmos.source.containers.includeAll` | `false` | Flag to indicate whether reading from all containers. | +| `azure.cosmos.source.containers.includedList` | `[]` | Containers included. This config will be ignored if azure.cosmos.source.containers.includeAll is true. | +| `azure.cosmos.source.containers.topicMap` | `[]` | A comma delimited list of Kafka topics mapped to Cosmos containers. For example: topic1#con1,topic2#con2. By default, container name is used as the name of the kafka topic to publish data to, can use this property to override the default config | +| `azure.cosmos.source.changeFeed.startFrom` | `Beginning` | ChangeFeed Start from settings (Now, Beginning or a certain point in time (UTC) for example 2020-02-10T14:15:03) - the default value is 'Beginning'. | +| `azure.cosmos.source.changeFeed.mode` | `LatestVersion` | ChangeFeed mode (LatestVersion or AllVersionsAndDeletes). | +| `azure.cosmos.source.changeFeed.maxItemCountHint` | `1000` | The maximum number of documents returned in a single change feed request. But the number of items received might be higher than the specified value if multiple items are changed by the same transaction. | +| `azure.cosmos.source.metadata.poll.delay.ms` | `300000` | Indicates how often to check the metadata changes (including container split/merge, adding/removing/recreated containers). When changes are detected, it will reconfigure the tasks. Default is 5 minutes. | +| `azure.cosmos.source.metadata.storage.type` | `Kafka` | The storage type of the metadata. Two types are supported: Cosmos, Kafka. | +| `azure.cosmos.source.metadata.storage.name` | `_cosmos.metadata.topic` | The resource name of the metadata storage. If metadata storage type is Kafka topic, then this config refers to kafka topic name, the metadata topic will be created if it does not already exist, else it will use the pre-created topic. If metadata storage type is `Cosmos`, then this config refers to container name, for `MasterKey` auth, this container will be created with `AutoScale` with 4000 RU if not already exists, for `ServicePrincipal` auth, it requires the container to be created ahead of time . | +| `azure.cosmos.source.messageKey.enabled` | `true` | Whether to set the kafka record message key. | +| `azure.cosmos.source.messageKey.field` | `id` | The field to use as the message key. | ## Sink Connector Configuration -| Config Property Name | Default | Description | -|:-------------------------------------------------------|:--------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `azure.cosmos.sink.database.name` | `""` | Cosmos DB database name. | -| `azure.cosmos.sink.containers.topicMap` | `""` | A comma delimited list of Kafka topics mapped to Cosmos containers. For example: topic1#con1,topic2#con2. | -| `azure.cosmos.sink.errors.tolerance.level` | `None` | Error tolerance level after exhausting all retries. `None` for fail on error. `All` for log and continue | -| `azure.cosmos.sink.bulk.enabled` | `true` | Flag to indicate whether Cosmos DB bulk mode is enabled for Sink connector. By default it is true. | -| `azure.cosmos.sink.bulk.maxConcurrentCosmosPartitions` | `-1` | Cosmos DB Item Write Max Concurrent Cosmos Partitions. If not specified it will be determined based on the number of the container's physical partitions which would indicate every batch is expected to have data from all Cosmos physical partitions. If specified it indicates from at most how many Cosmos Physical Partitions each batch contains data. So this config can be used to make bulk processing more efficient when input data in each batch has been repartitioned to balance to how many Cosmos partitions each batch needs to write. This is mainly useful for very large containers (with hundreds of physical partitions. | -| `azure.cosmos.sink.bulk.initialBatchSize` | `1` | Cosmos DB initial bulk micro batch size - a micro batch will be flushed to the backend when the number of documents enqueued exceeds this size - or the target payload size is met. The micro batch size is getting automatically tuned based on the throttling rate. By default the initial micro batch size is 1. Reduce this when you want to avoid that the first few requests consume too many RUs. | -| `azure.cosmos.sink.write.strategy` | `ItemOverwrite` | Cosmos DB Item write Strategy: `ItemOverwrite` (using upsert), `ItemAppend` (using create, ignore pre-existing items i.e., Conflicts), `ItemDelete` (deletes based on id/pk of data frame), `ItemDeleteIfNotModified` (deletes based on id/pk of data frame if etag hasn't changed since collecting id/pk), `ItemOverwriteIfNotModified` (using create if etag is empty, update/replace with etag pre-condition otherwise, if document was updated the pre-condition failure is ignored), `ItemPatch` (Partial update all documents based on the patch config) | -| `azure.cosmos.sink.maxRetryCount` | `10` | Cosmos DB max retry attempts on write failures for Sink connector. By default, the connector will retry on transient write errors for up to 10 times. | -| `azure.cosmos.sink.id.strategy` | `ProvidedInValueStrategy` | A strategy used to populate the document with an ``id``. Valid strategies are: ``TemplateStrategy``, ``FullKeyStrategy``, ``KafkaMetadataStrategy``, ``ProvidedInKeyStrategy``, ``ProvidedInValueStrategy``. Configuration properties prefixed with``id.strategy`` are passed through to the strategy. For example, when using ``id.strategy=TemplateStrategy`` , the property ``id.strategy.template`` is passed through to the template strategy and used to specify the template string to be used in constructing the ``id``. | -| `azure.cosmos.sink.write.patch.operationType.default` | `Set` | Default Cosmos DB patch operation type. Supported ones include none, add, set, replace, remove, increment. Choose none for no-op, for others please reference [here](https://docs.microsoft.com/azure/cosmos-db/partial-document-update#supported-operations) for full context. | -| `azure.cosmos.sink.write.patch.property.configs` | `""` | Cosmos DB patch json property configs. It can contain multiple definitions matching the following patterns separated by comma. property(jsonProperty).op(operationType) or property(jsonProperty).path(patchInCosmosdb).op(operationType) - The difference of the second pattern is that it also allows you to define a different cosmosdb path. Note: It does not support nested json property config. | -| `azure.cosmos.sink.write.patch.filter` | `""` | Used for [Conditional patch](https://docs.microsoft.com/azure/cosmos-db/partial-document-update-getting-started#java) | +| Config Property Name | Default | Description | +|:-----------------------------------------------------------|:--------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `azure.cosmos.sink.database.name` | `""` | Cosmos DB database name. | +| `azure.cosmos.sink.containers.topicMap` | `""` | A comma delimited list of Kafka topics mapped to Cosmos containers. For example: topic1#con1,topic2#con2. | +| `azure.cosmos.sink.errors.tolerance.level` | `None` | Error tolerance level after exhausting all retries. `None` for fail on error. `All` for log and continue | +| `azure.cosmos.sink.bulk.enabled` | `true` | Flag to indicate whether Cosmos DB bulk mode is enabled for Sink connector. By default it is true. | +| `azure.cosmos.sink.bulk.maxConcurrentCosmosPartitions` | `-1` | Cosmos DB Item Write Max Concurrent Cosmos Partitions. If not specified it will be determined based on the number of the container's physical partitions which would indicate every batch is expected to have data from all Cosmos physical partitions. If specified it indicates from at most how many Cosmos Physical Partitions each batch contains data. So this config can be used to make bulk processing more efficient when input data in each batch has been repartitioned to balance to how many Cosmos partitions each batch needs to write. This is mainly useful for very large containers (with hundreds of physical partitions. | +| `azure.cosmos.sink.bulk.initialBatchSize` | `1` | Cosmos DB initial bulk micro batch size - a micro batch will be flushed to the backend when the number of documents enqueued exceeds this size - or the target payload size is met. The micro batch size is getting automatically tuned based on the throttling rate. By default the initial micro batch size is 1. Reduce this when you want to avoid that the first few requests consume too many RUs. | +| `azure.cosmos.sink.write.strategy` | `ItemOverwrite` | Cosmos DB Item write Strategy: `ItemOverwrite` (using upsert), `ItemAppend` (using create, ignore pre-existing items i.e., Conflicts), `ItemDelete` (deletes based on id/pk of data frame), `ItemDeleteIfNotModified` (deletes based on id/pk of data frame if etag hasn't changed since collecting id/pk), `ItemOverwriteIfNotModified` (using create if etag is empty, update/replace with etag pre-condition otherwise, if document was updated the pre-condition failure is ignored), `ItemPatch` (Partial update all documents based on the patch config) | +| `azure.cosmos.sink.maxRetryCount` | `10` | Cosmos DB max retry attempts on write failures for Sink connector. By default, the connector will retry on transient write errors for up to 10 times. | +| `azure.cosmos.sink.id.strategy` | `ProvidedInValueStrategy` | A strategy used to populate the document with an ``id``. Valid strategies are: ``TemplateStrategy``, ``FullKeyStrategy``, ``KafkaMetadataStrategy``, ``ProvidedInKeyStrategy``, ``ProvidedInValueStrategy``. Configuration properties prefixed with``id.strategy`` are passed through to the strategy. For example, when using ``id.strategy=TemplateStrategy`` , the property ``id.strategy.template`` is passed through to the template strategy and used to specify the template string to be used in constructing the ``id``. | +| `azure.cosmos.sink.write.patch.operationType.default` | `Set` | Default Cosmos DB patch operation type. Supported ones include none, add, set, replace, remove, increment. Choose none for no-op, for others please reference [here](https://docs.microsoft.com/azure/cosmos-db/partial-document-update#supported-operations) for full context. | +| `azure.cosmos.sink.write.patch.property.configs` | `""` | Cosmos DB patch json property configs. It can contain multiple definitions matching the following patterns separated by comma. property(jsonProperty).op(operationType) or property(jsonProperty).path(patchInCosmosdb).op(operationType) - The difference of the second pattern is that it also allows you to define a different cosmosdb path. Note: It does not support nested json property config. | +| `azure.cosmos.sink.write.patch.filter` | `""` | Used for [Conditional patch](https://docs.microsoft.com/azure/cosmos-db/partial-document-update-getting-started#java) | diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml b/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml index f6c377b7b505b..ae5e2dfef8f85 100644 --- a/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml +++ b/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml @@ -13,7 +13,7 @@ Licensed under the MIT License. com.azure.cosmos.kafka azure-cosmos-kafka-connect - 1.0.0-beta.2 + 1.0.0-beta.3 Apache Kafka Connect connector for Azure Cosmos DB This Package contains an Apache Kafka Connect source and sink connector for Azure Cosmos DB jar @@ -82,7 +82,7 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.59.0 + 4.60.0-beta.1 + 1.12.1 com.azure diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/src/main/java/com/azure/cosmos/kafka/connect/CosmosSourceConnector.java b/sdk/cosmos/azure-cosmos-kafka-connect/src/main/java/com/azure/cosmos/kafka/connect/CosmosSourceConnector.java index b91bff22f3414..baf6cc6f73737 100644 --- a/sdk/cosmos/azure-cosmos-kafka-connect/src/main/java/com/azure/cosmos/kafka/connect/CosmosSourceConnector.java +++ b/sdk/cosmos/azure-cosmos-kafka-connect/src/main/java/com/azure/cosmos/kafka/connect/CosmosSourceConnector.java @@ -9,6 +9,7 @@ import com.azure.cosmos.implementation.apachecommons.lang.RandomUtils; import com.azure.cosmos.implementation.apachecommons.lang.tuple.Pair; import com.azure.cosmos.kafka.connect.implementation.CosmosClientStore; +import com.azure.cosmos.kafka.connect.implementation.CosmosMasterKeyAuthConfig; import com.azure.cosmos.kafka.connect.implementation.KafkaCosmosConstants; import com.azure.cosmos.kafka.connect.implementation.KafkaCosmosExceptionsHelper; import com.azure.cosmos.kafka.connect.implementation.source.CosmosMetadataStorageType; @@ -25,12 +26,15 @@ import com.azure.cosmos.kafka.connect.implementation.source.MetadataMonitorThread; import com.azure.cosmos.kafka.connect.implementation.source.MetadataTaskUnit; import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.CosmosContainerResponse; import com.azure.cosmos.models.FeedRange; import com.azure.cosmos.models.PartitionKeyDefinition; +import com.azure.cosmos.models.ThroughputProperties; import org.apache.kafka.common.config.Config; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigValue; import org.apache.kafka.connect.connector.Task; +import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.source.SourceConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -57,6 +61,7 @@ public final class CosmosSourceConnector extends SourceConnector implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosSourceConnector.class); private static final String CONNECTOR_NAME = "name"; + private static final int METADATA_CONTAINER_DEFAULT_RU_CONFIG = 4000; private CosmosSourceConfig config; private CosmosAsyncClient cosmosClient; @@ -167,6 +172,14 @@ private IMetadataReader getMetadataReader() { throw new IllegalStateException("Cosmos Metadata container need to be partitioned by /id"); } }) + .onErrorResume(throwable -> { + if (KafkaCosmosExceptionsHelper.isNotFoundException(throwable) + && shouldCreateMetadataContainerIfNotExists()) { + return createMetadataContainer(); + } + + return Mono.error(new ConnectException(throwable)); + }) .block(); return new MetadataCosmosStorageManager(metadataContainer); default: @@ -174,6 +187,22 @@ private IMetadataReader getMetadataReader() { } } + private boolean shouldCreateMetadataContainerIfNotExists() { + // If customer does not create the metadata container ahead of time, + // then SDK will create one with default autoScale config only if using masterKey auth. + return this.config.getMetadataConfig().getStorageType() == CosmosMetadataStorageType.COSMOS + && (this.config.getAccountConfig().getCosmosAuthConfig() instanceof CosmosMasterKeyAuthConfig); + } + + private Mono createMetadataContainer() { + return this.cosmosClient + .getDatabase(this.config.getContainersConfig().getDatabaseName()) + .createContainer( + this.config.getMetadataConfig().getStorageName(), + "/id", + ThroughputProperties.createAutoscaledThroughput(METADATA_CONTAINER_DEFAULT_RU_CONFIG)); + } + private void updateMetadataRecordsInCosmos(MetadataTaskUnit metadataTaskUnit) { if (metadataTaskUnit.getStorageType() != CosmosMetadataStorageType.COSMOS) { throw new IllegalStateException("updateMetadataRecordsInCosmos should not be called when metadata storage type is not cosmos"); diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/src/main/java/com/azure/cosmos/kafka/connect/implementation/source/CosmosSourceConfig.java b/sdk/cosmos/azure-cosmos-kafka-connect/src/main/java/com/azure/cosmos/kafka/connect/implementation/source/CosmosSourceConfig.java index 2cc8ee56c734f..ba7a2821ac209 100644 --- a/sdk/cosmos/azure-cosmos-kafka-connect/src/main/java/com/azure/cosmos/kafka/connect/implementation/source/CosmosSourceConfig.java +++ b/sdk/cosmos/azure-cosmos-kafka-connect/src/main/java/com/azure/cosmos/kafka/connect/implementation/source/CosmosSourceConfig.java @@ -79,8 +79,9 @@ public class CosmosSourceConfig extends KafkaCosmosConfig { private static final String DEFAULT_METADATA_STORAGE_TYPE = CosmosMetadataStorageType.KAFKA.getName(); private static final String METADATA_STORAGE_NAME = "azure.cosmos.source.metadata.storage.name"; - private static final String METADATA_STORAGE_NAME_DOC = "The resource name of the metadata storage. If metadata storage type is Kafka topic, then this config refers to kafka topic name, the metadata topic will be created if it does not already exist, else it will use the pre-created topic." - + " If metadata storage type is CosmosDB container, then this config refers to container name, please pre-create the metadata container partitioned by /id."; + private static final String METADATA_STORAGE_NAME_DOC = "The resource name of the metadata storage." + + " If metadata storage type is Kafka topic, then this config refers to kafka topic name, the metadata topic will be created if it does not already exist, else it will use the pre-created topic." + + " If metadata storage type is `Cosmos`, then this config refers to container name, for `MasterKey` auth, this container will be created with `AutoScale` with 4000 RU if not already exists, for `ServicePrincipal` auth, it requires the container to be created ahead of time ."; private static final String METADATA_STORAGE_NAME_DISPLAY = "The metadata storage name."; private static final String DEFAULT_METADATA_STORAGE_NAME = "_cosmos.metadata.topic"; diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/src/test/java/com/azure/cosmos/kafka/connect/CosmosSourceConnectorITest.java b/sdk/cosmos/azure-cosmos-kafka-connect/src/test/java/com/azure/cosmos/kafka/connect/CosmosSourceConnectorITest.java index d34caf8f4c9ce..5e0fe97eb90b0 100644 --- a/sdk/cosmos/azure-cosmos-kafka-connect/src/test/java/com/azure/cosmos/kafka/connect/CosmosSourceConnectorITest.java +++ b/sdk/cosmos/azure-cosmos-kafka-connect/src/test/java/com/azure/cosmos/kafka/connect/CosmosSourceConnectorITest.java @@ -23,10 +23,12 @@ import org.rnorth.ducttape.unreliables.Unreliables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.sourcelab.kafka.connect.apiclient.request.dto.ConnectorStatus; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import reactor.core.publisher.Mono; import java.time.Duration; import java.util.ArrayList; @@ -71,7 +73,17 @@ public static Object[][] sourceAuthParameterProvider() { }; } - // TODO[public preview]: add more integration tests + @DataProvider(name = "metadataCosmosStorageParameterProvider") + public static Object[][] metadataCosmosStorageParameterProvider() { + return new Object[][]{ + // use masterKey auth, pre-create the metadata container, should connector start successfully + { true, true, true }, + { true, false, true }, + { false, true, true }, + { false, false, false} + }; + } + @Test(groups = { "kafka-integration" }, dataProvider = "sourceAuthParameterProvider", timeOut = 2 * TIMEOUT) public void readFromSingleContainer(boolean useMasterKey, CosmosMetadataStorageType metadataStorageType) { logger.info("read from single container " + useMasterKey); @@ -211,4 +223,88 @@ public void readFromSingleContainer(boolean useMasterKey, CosmosMetadataStorageT } } } + + @Test(groups = { "kafka-integration" }, dataProvider = "metadataCosmosStorageParameterProvider", timeOut = 2 * TIMEOUT) + public void connectorStart_metadata_cosmosStorageType( + boolean useMasterKey, + boolean preCreateMetadataContainer, + boolean canConnectorStart) { + + String topicName = singlePartitionContainerName + "-" + UUID.randomUUID(); + String metadataStorageName = "Metadata-" + UUID.randomUUID(); + + Map sourceConnectorConfig = new HashMap<>(); + sourceConnectorConfig.put("connector.class", "com.azure.cosmos.kafka.connect.CosmosSourceConnector"); + sourceConnectorConfig.put("azure.cosmos.account.endpoint", KafkaCosmosTestConfigurations.HOST); + sourceConnectorConfig.put("azure.cosmos.application.name", "Test"); + sourceConnectorConfig.put("azure.cosmos.source.database.name", databaseName); + sourceConnectorConfig.put("azure.cosmos.source.containers.includeAll", "false"); + sourceConnectorConfig.put("azure.cosmos.source.containers.includedList", singlePartitionContainerName); + sourceConnectorConfig.put("azure.cosmos.source.containers.topicMap", topicName + "#" + singlePartitionContainerName); + sourceConnectorConfig.put("azure.cosmos.source.metadata.storage.name", metadataStorageName); + sourceConnectorConfig.put("azure.cosmos.source.metadata.storage.type", CosmosMetadataStorageType.COSMOS.getName()); + + if (useMasterKey) { + sourceConnectorConfig.put("azure.cosmos.account.key", KafkaCosmosTestConfigurations.MASTER_KEY); + } else { + sourceConnectorConfig.put("azure.cosmos.auth.type", CosmosAuthType.SERVICE_PRINCIPAL.getName()); + sourceConnectorConfig.put("azure.cosmos.account.tenantId", KafkaCosmosTestConfigurations.ACCOUNT_TENANT_ID); + sourceConnectorConfig.put("azure.cosmos.auth.aad.clientId", KafkaCosmosTestConfigurations.ACCOUNT_AAD_CLIENT_ID); + sourceConnectorConfig.put("azure.cosmos.auth.aad.clientSecret", KafkaCosmosTestConfigurations.ACCOUNT_AAD_CLIENT_SECRET); + } + + // Create topic ahead of time + kafkaCosmosConnectContainer.createTopic(topicName, 1); + + String connectorName = "simpleTest-" + UUID.randomUUID(); + + try { + // if using cosmos container to persiste the metadata, pre-create it + if (preCreateMetadataContainer) { + logger.info("Creating metadata container"); + client.getDatabase(databaseName) + .createContainerIfNotExists(metadataStorageName, "/id") + .block(); + } else { + logger.info("Skip creating metadata container"); + } + + kafkaCosmosConnectContainer.registerConnector(connectorName, sourceConnectorConfig); + + Thread.sleep(10000); // give some time for the connector to start up + // verify connector tasks + ConnectorStatus connectorStatus = kafkaCosmosConnectContainer.getConnectorStatus(connectorName); + if (canConnectorStart) { + assertThat(connectorStatus.getConnector().get("state").equals("RUNNING")).isTrue(); + } else { + assertThat(connectorStatus.getConnector().get("state").equals("FAILED")).isTrue(); + } + + } catch (InterruptedException e) { + throw new RuntimeException(e); + } finally { + if (client != null) { + logger.info("cleaning container {}", singlePartitionContainerName); + cleanUpContainer(client, databaseName, singlePartitionContainerName); + + // delete the metadata container if created + if (preCreateMetadataContainer || canConnectorStart) { + client + .getDatabase(databaseName) + .getContainer(metadataStorageName) + .delete() + .onErrorResume(throwable -> { + logger.error("Deleting metadata container failed ", throwable); + return Mono.empty(); + }) + .block(); + } + } + + // IMPORTANT: remove the connector after use + if (kafkaCosmosConnectContainer != null) { + kafkaCosmosConnectContainer.deleteConnector(connectorName); + } + } + } } diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/src/test/java/com/azure/cosmos/kafka/connect/KafkaCosmosConnectContainer.java b/sdk/cosmos/azure-cosmos-kafka-connect/src/test/java/com/azure/cosmos/kafka/connect/KafkaCosmosConnectContainer.java index 68fcd36097536..8047e676ac109 100644 --- a/sdk/cosmos/azure-cosmos-kafka-connect/src/test/java/com/azure/cosmos/kafka/connect/KafkaCosmosConnectContainer.java +++ b/sdk/cosmos/azure-cosmos-kafka-connect/src/test/java/com/azure/cosmos/kafka/connect/KafkaCosmosConnectContainer.java @@ -12,6 +12,7 @@ import org.sourcelab.kafka.connect.apiclient.Configuration; import org.sourcelab.kafka.connect.apiclient.KafkaConnectClient; import org.sourcelab.kafka.connect.apiclient.request.dto.ConnectorDefinition; +import org.sourcelab.kafka.connect.apiclient.request.dto.ConnectorStatus; import org.sourcelab.kafka.connect.apiclient.request.dto.NewConnectorDefinition; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.KafkaContainer; @@ -181,6 +182,11 @@ public void deleteConnector(String name) { } } + public ConnectorStatus getConnectorStatus(String name) { + KafkaConnectClient kafkaConnectClient = new KafkaConnectClient(new Configuration(getTarget())); + return kafkaConnectClient.getConnectorStatus(name); + } + public String getTarget() { return "http://" + getContainerIpAddress() + ":" + getMappedPort(KAFKA_CONNECT_PORT); } diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/pom.xml b/sdk/cosmos/azure-cosmos-spark_3_2-12/pom.xml index 32dcb40100d2d..53409ae7e7c85 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/pom.xml +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/pom.xml @@ -64,7 +64,7 @@ com.azure azure-cosmos - 4.59.0 + 4.60.0-beta.1 org.scala-lang.modules @@ -90,7 +90,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 com.azure @@ -101,7 +101,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure diff --git a/sdk/cosmos/azure-cosmos-test/CHANGELOG.md b/sdk/cosmos/azure-cosmos-test/CHANGELOG.md index 27bdb326a33cf..bb5bbe06a8534 100644 --- a/sdk/cosmos/azure-cosmos-test/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-test/CHANGELOG.md @@ -1,14 +1,9 @@ ## Release History -### 1.0.0-beta.7 (Unreleased) - -#### Features Added - -#### Breaking Changes +### 1.0.0-beta.7 (2024-05-03) #### Bugs Fixed - -#### Other Changes +* 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.6 (2023-10-24) #### Features Added diff --git a/sdk/cosmos/azure-cosmos-test/README.md b/sdk/cosmos/azure-cosmos-test/README.md index 4dde463568a12..ee05caf2a7041 100644 --- a/sdk/cosmos/azure-cosmos-test/README.md +++ b/sdk/cosmos/azure-cosmos-test/README.md @@ -9,7 +9,7 @@ Library containing core fault injection classes used to test Azure Cosmos DB SDK com.azure azure-cosmos-test - 1.0.0-beta.6 + 1.0.0-beta.7 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/cosmos/azure-cosmos-test/pom.xml b/sdk/cosmos/azure-cosmos-test/pom.xml index d0a3002d41b6c..cb2d32eb7ac6b 100644 --- a/sdk/cosmos/azure-cosmos-test/pom.xml +++ b/sdk/cosmos/azure-cosmos-test/pom.xml @@ -56,7 +56,7 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.59.0 + 4.59.0 diff --git a/sdk/cosmos/azure-cosmos-tests/pom.xml b/sdk/cosmos/azure-cosmos-tests/pom.xml index b792bb80148e0..b55fefbf13eae 100644 --- a/sdk/cosmos/azure-cosmos-tests/pom.xml +++ b/sdk/cosmos/azure-cosmos-tests/pom.xml @@ -99,7 +99,7 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.59.0 + 4.60.0-beta.1 com.azure @@ -150,7 +150,7 @@ Licensed under the MIT License. com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/faultinjection/FaultInjectionServerErrorRuleOnGatewayTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/faultinjection/FaultInjectionServerErrorRuleOnGatewayTests.java index 2be8f657c269d..524c9b86d0cd7 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/faultinjection/FaultInjectionServerErrorRuleOnGatewayTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/faultinjection/FaultInjectionServerErrorRuleOnGatewayTests.java @@ -75,7 +75,7 @@ public FaultInjectionServerErrorRuleOnGatewayTests(CosmosClientBuilder clientBui this.subscriberValidationTimeout = TIMEOUT; } - @BeforeClass(groups = {"multi-master", "long"}, timeOut = TIMEOUT) + @BeforeClass(groups = {"multi-master", "fast"}, timeOut = TIMEOUT) public void beforeClass() { client = getClientBuilder().buildAsyncClient(); AsyncDocumentClient asyncDocumentClient = BridgeInternal.getContextClient(client); @@ -225,79 +225,95 @@ public void faultInjectionServerErrorRuleTests_Region() throws JsonProcessingExc } } - @Test(groups = {"multi-master", "long"}, timeOut = 4 * TIMEOUT) + @Test(groups = {"multi-master", "fast"}, timeOut = 4 * TIMEOUT) public void faultInjectionServerErrorRuleTests_Partition() throws JsonProcessingException { - for (int i = 0; i < 10; i++) { - cosmosAsyncContainer.createItem(TestItem.createNewItem()).block(); - } + CosmosAsyncClient testClient = null; - // getting one item from each feedRange - List feedRanges = cosmosAsyncContainer.getFeedRanges().block(); - assertThat(feedRanges.size()).isGreaterThan(1); + try { + testClient = this.getClientBuilder() + .consistencyLevel(this.databaseAccount.getConsistencyPolicy().getDefaultConsistencyLevel()) + .buildAsyncClient(); - String query = "select * from c"; - CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); - cosmosQueryRequestOptions.setFeedRange(feedRanges.get(0)); - TestItem itemOnFeedRange0 = cosmosAsyncContainer.queryItems(query, cosmosQueryRequestOptions, TestItem.class).blockFirst(); + CosmosAsyncContainer testContainer = + testClient + .getDatabase(cosmosAsyncContainer.getDatabase().getId()) + .getContainer(cosmosAsyncContainer.getId()); - cosmosQueryRequestOptions.setFeedRange(feedRanges.get(1)); - TestItem itemOnFeedRange1 = cosmosAsyncContainer.queryItems(query, cosmosQueryRequestOptions, TestItem.class).blockFirst(); + for (int i = 0; i < 10; i++) { + testContainer.createItem(TestItem.createNewItem()).block(); + } - // set rule by feed range - String feedRangeRuleId = "ServerErrorRule-FeedRange-" + UUID.randomUUID(); + // getting one item from each feedRange + List feedRanges = testContainer.getFeedRanges().block(); + assertThat(feedRanges.size()).isGreaterThan(1); + + String query = "select * from c"; + CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); + cosmosQueryRequestOptions.setFeedRange(feedRanges.get(0)); + TestItem itemOnFeedRange0 = testContainer.queryItems(query, cosmosQueryRequestOptions, TestItem.class).blockFirst(); + + cosmosQueryRequestOptions.setFeedRange(feedRanges.get(1)); + TestItem itemOnFeedRange1 = testContainer.queryItems(query, cosmosQueryRequestOptions, TestItem.class).blockFirst(); + + // set rule by feed range + String feedRangeRuleId = "ServerErrorRule-FeedRange-" + UUID.randomUUID(); + + FaultInjectionRule serverErrorRuleByFeedRange = + new FaultInjectionRuleBuilder(feedRangeRuleId) + .condition( + new FaultInjectionConditionBuilder() + .connectionType(FaultInjectionConnectionType.GATEWAY) + .endpoints(new FaultInjectionEndpointBuilder(feedRanges.get(0)).build()) + .build() + ) + .result( + FaultInjectionResultBuilders + .getResultBuilder(FaultInjectionServerErrorType.TOO_MANY_REQUEST) + .times(1) + .build() + ) + .duration(Duration.ofMinutes(5)) + .build(); + + CosmosFaultInjectionHelper.configureFaultInjectionRules(testContainer, Arrays.asList(serverErrorRuleByFeedRange)).block(); + assertThat( + serverErrorRuleByFeedRange.getRegionEndpoints().size() == this.readRegionMap.size() + && serverErrorRuleByFeedRange.getRegionEndpoints().containsAll(this.readRegionMap.keySet())); - FaultInjectionRule serverErrorRuleByFeedRange = - new FaultInjectionRuleBuilder(feedRangeRuleId) - .condition( - new FaultInjectionConditionBuilder() - .connectionType(FaultInjectionConnectionType.GATEWAY) - .endpoints(new FaultInjectionEndpointBuilder(feedRanges.get(0)).build()) - .build() - ) - .result( - FaultInjectionResultBuilders - .getResultBuilder(FaultInjectionServerErrorType.TOO_MANY_REQUEST) - .times(1) - .build() - ) - .duration(Duration.ofMinutes(5)) - .build(); + // Issue a read item for the same feed range as configured in the fault injection rule + CosmosDiagnostics cosmosDiagnostics = + testContainer + .readItem(itemOnFeedRange0.getId(), new PartitionKey(itemOnFeedRange0.getId()), JsonNode.class) + .block() + .getDiagnostics(); - CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(serverErrorRuleByFeedRange)).block(); - assertThat( - serverErrorRuleByFeedRange.getRegionEndpoints().size() == this.readRegionMap.size() - && serverErrorRuleByFeedRange.getRegionEndpoints().containsAll(this.readRegionMap.keySet())); - - // Issue a read item for the same feed range as configured in the fault injection rule - CosmosDiagnostics cosmosDiagnostics = - cosmosAsyncContainer - .readItem(itemOnFeedRange0.getId(), new PartitionKey(itemOnFeedRange0.getId()), JsonNode.class) - .block() - .getDiagnostics(); - - this.validateHitCount(serverErrorRuleByFeedRange, 1, OperationType.Read, ResourceType.Document); - this.validateFaultInjectionRuleApplied( - cosmosDiagnostics, - OperationType.Read, - HttpConstants.StatusCodes.TOO_MANY_REQUESTS, - HttpConstants.SubStatusCodes.USER_REQUEST_RATE_TOO_LARGE, - feedRangeRuleId, - true - ); - - // Issue a read item to different feed range - try { - cosmosDiagnostics = cosmosAsyncContainer - .readItem(itemOnFeedRange1.getId(), new PartitionKey(itemOnFeedRange1.getId()), JsonNode.class) - .block() - .getDiagnostics(); - this.validateNoFaultInjectionApplied(cosmosDiagnostics, OperationType.Read, FAULT_INJECTION_RULE_NON_APPLICABLE_ADDRESS); + this.validateHitCount(serverErrorRuleByFeedRange, 1, OperationType.Read, ResourceType.Document); + this.validateFaultInjectionRuleApplied( + cosmosDiagnostics, + OperationType.Read, + HttpConstants.StatusCodes.TOO_MANY_REQUESTS, + HttpConstants.SubStatusCodes.USER_REQUEST_RATE_TOO_LARGE, + feedRangeRuleId, + true + ); + + // Issue a read item to different feed range + try { + cosmosDiagnostics = testContainer + .readItem(itemOnFeedRange1.getId(), new PartitionKey(itemOnFeedRange1.getId()), JsonNode.class) + .block() + .getDiagnostics(); + this.validateNoFaultInjectionApplied(cosmosDiagnostics, OperationType.Read, FAULT_INJECTION_RULE_NON_APPLICABLE_ADDRESS); + } finally { + serverErrorRuleByFeedRange.disable(); + } } finally { - serverErrorRuleByFeedRange.disable(); + safeClose(testClient); } + } - @Test(groups = {"multi-master", "long"}, timeOut = 4 * TIMEOUT) + @Test(groups = {"multi-master", "fast"}, timeOut = 4 * TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerResponseDelay() throws JsonProcessingException { // define another rule which can simulate timeout String timeoutRuleId = "serverErrorRule-responseDelay-" + UUID.randomUUID(); @@ -347,7 +363,7 @@ public void faultInjectionServerErrorRuleTests_ServerResponseDelay() throws Json } } - @Test(groups = {"multi-master", "long"}, timeOut = 4 * TIMEOUT) + @Test(groups = {"multi-master", "fast"}, timeOut = 4 * TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerConnectionDelay() throws JsonProcessingException { // simulate high channel acquisition/connectionTimeout String ruleId = "serverErrorRule-serverConnectionDelay-" + UUID.randomUUID(); @@ -388,7 +404,7 @@ public void faultInjectionServerErrorRuleTests_ServerConnectionDelay() throws Js } } - @Test(groups = {"multi-master", "long"}, dataProvider = "faultInjectionServerErrorResponseProvider", timeOut = TIMEOUT) + @Test(groups = {"multi-master", "fast"}, dataProvider = "faultInjectionServerErrorResponseProvider", timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerErrorResponse( FaultInjectionServerErrorType serverErrorType, boolean canRetry, @@ -460,7 +476,7 @@ public void faultInjectionServerErrorRuleTests_ServerErrorResponse( } } - @Test(groups = {"multi-master", "long"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) + @Test(groups = {"multi-master", "fast"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_HitLimit( OperationType operationType, FaultInjectionOperationType faultInjectionOperationType) throws JsonProcessingException { @@ -518,7 +534,7 @@ public void faultInjectionServerErrorRuleTests_HitLimit( } } - @AfterClass(groups = {"multi-master", "long"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + @AfterClass(groups = {"multi-master", "fast"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index 7586e505b1e86..4ea8a84052bdb 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -1,5 +1,15 @@ ## Release History +### 4.60.0-beta.1 (Unreleased) + +#### Features Added + +#### Breaking Changes + +#### Bugs Fixed + +#### Other Changes + ### 4.59.0 (2024-04-27) #### Features Added @@ -8,6 +18,11 @@ #### Other Changes * Load Blackbird or Afterburner into the ObjectMapper depending upon Java version and presence of modules in classpath. Make Afterburner and Blackbird optional maven dependencies. See - [PR 39689](https://github.com/Azure/azure-sdk-for-java/pull/39689) +### 4.53.5-hotfix (2024-04-25) + +#### Bugs Fixed +* Fixed an issue in QuorumReader when quorum could not be selected even though 1 secondary and Primary are reachable and in sync. - See [PR 38832](https://github.com/Azure/azure-sdk-for-java/pull/38832) + ### 4.58.0 (2024-04-16) #### Other Changes * Changed initial `targetBatchSize` to be capped by both `initialBatchSize` and `maxBatchSize` configured in `CosmosBulkExecutionOptions` - See[39500](https://github.com/Azure/azure-sdk-for-java/pull/39500) @@ -29,6 +44,39 @@ * Changed logic to only call `System.exit()` in `DiagnosticsProvider` for `Error` scenario. Also added `System.err` for `Error` cases. - See [PR 39077](https://github.com/Azure/azure-sdk-for-java/pull/39077) * Removed `System.exit()` calls from `ImplementationBridgeHelpers`. - See [PR 39387](https://github.com/Azure/azure-sdk-for-java/pull/39387) +### 4.53.4-hotfix (2024-03-15) + +#### Other Changes +* Removed `System.exit()` calls from `ImplementationBridgeHelpers`. - See [PR 39215](https://github.com/Azure/azure-sdk-for-java/pull/39215) + +### 4.48.3-hotfix (2024-03-15) + +#### Bugs Fixed +* Fixed an issue where `sampleDiagnostics` is not being honored for `query. See [PR 37015](https://github.com/Azure/azure-sdk-for-java/pull/37015) +* Suppressed exceptions when calling diagnostics handlers. - See [PR 39077](https://github.com/Azure/azure-sdk-for-java/pull/39077) + +### Other Changes +* Changed logic to only call `System.exit()` in `DiagnosticsProvider` for `Error` scenario. Also added `System.err` for `Error` cases. - See [PR 39077](https://github.com/Azure/azure-sdk-for-java/pull/39077) +* Removed `System.exit()` calls from `ImplementationBridgeHelpers`. - See [PR 39182](https://github.com/Azure/azure-sdk-for-java/pull/39182) + +### 4.45.3-hotfix (2024-03-15) + +#### Bugs Fixed +* Fixed an issue where `sampleDiagnostics` is not being honored for `query. See [PR 37015](https://github.com/Azure/azure-sdk-for-java/pull/37015) +* Suppressed exceptions when calling diagnostics handlers. - See [PR 39077](https://github.com/Azure/azure-sdk-for-java/pull/39077) + +### Other Changes +* Changed logic to only call `System.exit()` in `DiagnosticsProvider` for `Error` scenario. Also added `System.err` for `Error` cases. - See [PR 39077](https://github.com/Azure/azure-sdk-for-java/pull/39077) +* Removed `System.exit()` calls from `ImplementationBridgeHelpers`. - See [PR 39184](https://github.com/Azure/azure-sdk-for-java/pull/39184) + +### 4.53.3-hotfix (2024-03-07) + +#### Bugs Fixed +* Suppressed exceptions when calling diagnostics handlers. - See [PR 39121](https://github.com/Azure/azure-sdk-for-java/pull/39121) + +#### Other Changes +* Changed logic to only call `System.exit()` in `DiagnosticsProvider` for `Error` scenario. Also added `System.err` for `Error` cases. - See [PR 39121](https://github.com/Azure/azure-sdk-for-java/pull/39121) + ### 4.56.0 (2024-02-20) #### Features Added @@ -57,6 +105,13 @@ * Added an option to opt-out of E2E timeout defined in CosmosClientBuilder for non-point operations via system property or environment variable. - See [PR 38388](https://github.com/Azure/azure-sdk-for-java/pull/38388) * Using `ConnectionTimeout` as the `RNTBD` connection `acquisitionTimeout`. - See [PR 38695](https://github.com/Azure/azure-sdk-for-java/pull/38695) +### 4.53.2-hotfix (2024-02-04) + +#### Other Changes +* Reduced CPU overhead slightly for workloads with high throughput of point operations - especially when diagnostics like traces or metrics are enabled. - See [PR 38232](https://github.com/Azure/azure-sdk-for-java/pull/38232) +* Changed to add `transportRequestChannelAcquisitionContext` in CosmosDiagnostics based on duration in `channelAcquisitionStarted` stage. By default, if `channelAcquisitionStarted` took more than 1s, `transportRequestChannelAcquisitionContext` will be added. - See [PR 38416](https://github.com/Azure/azure-sdk-for-java/pull/38416) +* Added an option to opt-out of E2E timeout defined in CosmosClientBuilder for non-point operations via system property or environment variable. - See [PR 38388](https://github.com/Azure/azure-sdk-for-java/pull/38388) + ### 4.54.0 (2024-01-03) #### Features Added @@ -70,31 +125,6 @@ * Reset `transitTimeoutCount` and `cancellationCount` in `RntbdClientChannelHealthChecker` when CPU load is above threshold. - See [PR 38157](https://github.com/Azure/azure-sdk-for-java/pull/38157) * Perf-improvement avoiding extra-buffer copy for query and point operations - See [PR 38072](https://github.com/Azure/azure-sdk-for-java/pull/38072) -### 4.53.5-hotfix (2024-04-25) - -#### Bugs Fixed -* Fixed an issue in QuorumReader when quorum could not be selected even though 1 secondary and Primary are reachable and in sync. - See [PR 38832](https://github.com/Azure/azure-sdk-for-java/pull/38832) - -### 4.53.4-hotfix (2024-03-15) - -#### Other Changes -* Removed `System.exit()` calls from `ImplementationBridgeHelpers`. - See [PR 39215](https://github.com/Azure/azure-sdk-for-java/pull/39215) - -### 4.53.3-hotfix (2024-03-07) - -#### Bugs Fixed -* Suppressed exceptions when calling diagnostics handlers. - See [PR 39121](https://github.com/Azure/azure-sdk-for-java/pull/39121) - -#### Other Changes -* Changed logic to only call `System.exit()` in `DiagnosticsProvider` for `Error` scenario. Also added `System.err` for `Error` cases. - See [PR 39121](https://github.com/Azure/azure-sdk-for-java/pull/39121) - -### 4.53.2-hotfix (2024-02-04) - -#### Other Changes -* Reduced CPU overhead slightly for workloads with high throughput of point operations - especially when diagnostics like traces or metrics are enabled. - See [PR 38232](https://github.com/Azure/azure-sdk-for-java/pull/38232) -* Changed to add `transportRequestChannelAcquisitionContext` in CosmosDiagnostics based on duration in `channelAcquisitionStarted` stage. By default, if `channelAcquisitionStarted` took more than 1s, `transportRequestChannelAcquisitionContext` will be added. - See [PR 38416](https://github.com/Azure/azure-sdk-for-java/pull/38416) -* Added an option to opt-out of E2E timeout defined in CosmosClientBuilder for non-point operations via system property or environment variable. - See [PR 38388](https://github.com/Azure/azure-sdk-for-java/pull/38388) - ### 4.53.1 (2023-12-06) #### Bugs Fixed @@ -162,6 +192,28 @@ * Handling negative end-to-end timeouts provided more gracefully by throwing a `CosmsoException` (`OperationCancelledException`) instead of `IllegalArgumentException`. - See [PR 36507](https://github.com/Azure/azure-sdk-for-java/pull/36507) * Reverted preserve ordering in bulk mode([PR 35892](https://github.com/Azure/azure-sdk-for-java/pull/35892)). See [PR 36638](https://github.com/Azure/azure-sdk-for-java/pull/36638) +### 4.45.2-hotfix (2023-09-18) +> [!IMPORTANT] +> We strongly recommend our customers to upgrade directly to at least 4.48.2 or above if they have been using the 4.45.2-hotfix version of `azure-cosmos`. Versions 4.46.0 - 4.48.1 will miss important fixes that have been backported to 4.45.2-hotfix. +#### Bugs Fixed +* Added capability to mark a region as unavailable when a request is cancelled due to end-to-end timeout and connection issues + with the region in the direct connectivity mode. - See [PR 35586](https://github.com/Azure/azure-sdk-for-java/pull/35586) +* Fixed an issue where `ConnectionStateListener` tracked staled `Uris` which fails to mark the current `Uris` unhealthy properly - See [PR 36067](https://github.com/Azure/azure-sdk-for-java/pull/36067) +* Fixed an issue to update the last unhealthy timestamp for an `Uri` instance only when transitioning to `Unhealthy` from a different health status - See [36083](https://github.com/Azure/azure-sdk-for-java/pull/36083) +* Improved the channel health check flow to deem a channel unhealthy when it sees consecutive cancellations. - See [PR 36225](https://github.com/Azure/azure-sdk-for-java/pull/36225) +* Optimized the replica validation flow to validate replica health with `Unknown` health status only when the replica is + used by a container which is also part of the connection warm-up flow. - See [PR 36225](https://github.com/Azure/azure-sdk-for-java/pull/36225) +* Fixed possible `NullPointerException` issue if health-check flow kicks in before RNTBD context negotiation for a given channel - See [PR 36397](https://github.com/Azure/azure-sdk-for-java/pull/36397). + +### 4.48.2 (2023-08-25) +> [!IMPORTANT] +> We strongly recommend our customers to use version 4.48.2 and above. +#### Bugs Fixed +* Fixed possible `NullPointerException` issue if health-check flow kicks in before RNTBD context negotiation for a given channel - See [PR 36397](https://github.com/Azure/azure-sdk-for-java/pull/36397). + +#### Other Changes +* Handling negative end-to-end timeouts provided more gracefully by throwing a `CosmosException` (`OperationCancelledException`) instead of `IllegalArgumentException`. - See [PR 36535](https://github.com/Azure/azure-sdk-for-java/pull/36535) + ### 4.49.0 (2023-08-21) #### Features Added * Added a flag for allowing customers to preserve ordering in bulk mode. See [PR 35892](https://github.com/Azure/azure-sdk-for-java/pull/35892) @@ -175,25 +227,6 @@ #### Other Changes * Added coverage for `ChangeFeedProcessor` in `Latest Version` change feed mode to read change feed from a custom start time for multi-write accounts. - See[PR 36257](https://github.com/Azure/azure-sdk-for-java/pull/36257) -### 4.48.3-hotfix (2024-03-15) - -#### Bugs Fixed -* Fixed an issue where `sampleDiagnostics` is not being honored for `query. See [PR 37015](https://github.com/Azure/azure-sdk-for-java/pull/37015) -* Suppressed exceptions when calling diagnostics handlers. - See [PR 39077](https://github.com/Azure/azure-sdk-for-java/pull/39077) - -### Other Changes -* Changed logic to only call `System.exit()` in `DiagnosticsProvider` for `Error` scenario. Also added `System.err` for `Error` cases. - See [PR 39077](https://github.com/Azure/azure-sdk-for-java/pull/39077) -* Removed `System.exit()` calls from `ImplementationBridgeHelpers`. - See [PR 39182](https://github.com/Azure/azure-sdk-for-java/pull/39182) - -### 4.48.2 (2023-08-25) -> [!IMPORTANT] -> We strongly recommend our customers to use version 4.48.2 and above. -#### Bugs Fixed -* Fixed possible `NullPointerException` issue if health-check flow kicks in before RNTBD context negotiation for a given channel - See [PR 36397](https://github.com/Azure/azure-sdk-for-java/pull/36397). - -#### Other Changes -* Handling negative end-to-end timeouts provided more gracefully by throwing a `CosmosException` (`OperationCancelledException`) instead of `IllegalArgumentException`. - See [PR 36535](https://github.com/Azure/azure-sdk-for-java/pull/36535) - ### 4.48.1 (2023-08-09) #### Bugs Fixed * Fixed request start time in the `CosmosDiagnostics` for individual request responses - See [PR 35705](https://github.com/Azure/azure-sdk-for-java/pull/35705) @@ -216,6 +249,10 @@ used by a container which is also part of the connection warm-up flow. - See [PR #### Other Changes * Added fault injection support for Gateway connection mode - See [PR 35378](https://github.com/Azure/azure-sdk-for-java/pull/35378) +### 4.37.2-hotfix (2023-07-17) +#### Bugs Fixed +* Fixed an issue with deserialization of `conflictResolutionTimestamp` for All versions and deletes change feed mode. - See [PR 35912](https://github.com/Azure/azure-sdk-for-java/pull/35912) + ### 4.47.0 (2023-06-26) #### Features Added * Added the capability to specify region switch hints through `CosmosClientBuilder#setSessionRetryOptions` for optimizing retries for `READ_SESSION_NOT_AVAILABLE` errors. - See [PR 35292](https://github.com/Azure/azure-sdk-for-java/pull/35292) @@ -247,29 +284,6 @@ there are non-existent document IDs also passed through the API - See [PR 35513] JVM configuration - `COSMOS.MIN_CONNECTION_POOL_SIZE_PER_ENDPOINT` - See [PR 34859](https://github.com/Azure/azure-sdk-for-java/pull/34859) * Extending maximum retry delay in `SessionTokenMismatchRetryPolicy`. - See [PR 35360](https://github.com/Azure/azure-sdk-for-java/pull/35360) -### 4.45.3-hotfix (2024-03-15) - -#### Bugs Fixed -* Fixed an issue where `sampleDiagnostics` is not being honored for `query. See [PR 37015](https://github.com/Azure/azure-sdk-for-java/pull/37015) -* Suppressed exceptions when calling diagnostics handlers. - See [PR 39077](https://github.com/Azure/azure-sdk-for-java/pull/39077) - -### Other Changes -* Changed logic to only call `System.exit()` in `DiagnosticsProvider` for `Error` scenario. Also added `System.err` for `Error` cases. - See [PR 39077](https://github.com/Azure/azure-sdk-for-java/pull/39077) -* Removed `System.exit()` calls from `ImplementationBridgeHelpers`. - See [PR 39184](https://github.com/Azure/azure-sdk-for-java/pull/39184) - -### 4.45.2-hotfix (2023-09-18) -> [!IMPORTANT] -> We strongly recommend our customers to upgrade directly to at least 4.48.2 or above if they have been using the 4.45.2-hotfix version of `azure-cosmos`. Versions 4.46.0 - 4.48.1 will miss important fixes that have been backported to 4.45.2-hotfix. -#### Bugs Fixed -* Added capability to mark a region as unavailable when a request is cancelled due to end-to-end timeout and connection issues - with the region in the direct connectivity mode. - See [PR 35586](https://github.com/Azure/azure-sdk-for-java/pull/35586) -* Fixed an issue where `ConnectionStateListener` tracked staled `Uris` which fails to mark the current `Uris` unhealthy properly - See [PR 36067](https://github.com/Azure/azure-sdk-for-java/pull/36067) -* Fixed an issue to update the last unhealthy timestamp for an `Uri` instance only when transitioning to `Unhealthy` from a different health status - See [36083](https://github.com/Azure/azure-sdk-for-java/pull/36083) -* Improved the channel health check flow to deem a channel unhealthy when it sees consecutive cancellations. - See [PR 36225](https://github.com/Azure/azure-sdk-for-java/pull/36225) -* Optimized the replica validation flow to validate replica health with `Unknown` health status only when the replica is - used by a container which is also part of the connection warm-up flow. - See [PR 36225](https://github.com/Azure/azure-sdk-for-java/pull/36225) -* Fixed possible `NullPointerException` issue if health-check flow kicks in before RNTBD context negotiation for a given channel - See [PR 36397](https://github.com/Azure/azure-sdk-for-java/pull/36397). - ### 4.45.1 (2023-05-19) #### Bugs Fixed * Fixed an issue where status code & sub-status code `408/20008` will always be populated in the CosmosDiagnostics in case of `RNTBD` request failures - See [PR 34999](https://github.com/Azure/azure-sdk-for-java/pull/34999) @@ -382,10 +396,6 @@ there are non-existent document IDs also passed through the API - See [PR 35513] #### Features Added * Added option to set throughput control group name on per-request level for batch and bulk operations. - See [PR 31362](https://github.com/Azure/azure-sdk-for-java/pull/31362) -### 4.37.2-hotfix (2023-07-17) -#### Bugs Fixed -* Fixed an issue with deserialization of `conflictResolutionTimestamp` for All versions and deletes change feed mode. - See [PR 35912](https://github.com/Azure/azure-sdk-for-java/pull/35912) - ### 4.37.1 (2022-10-07) #### Bugs Fixed * Fixed incorrect RU metric reporting in micrometer metrics. - See [PR 31307](https://github.com/Azure/azure-sdk-for-java/pull/31307) diff --git a/sdk/cosmos/azure-cosmos/pom.xml b/sdk/cosmos/azure-cosmos/pom.xml index 40608deed97ce..b7270df0e39e6 100644 --- a/sdk/cosmos/azure-cosmos/pom.xml +++ b/sdk/cosmos/azure-cosmos/pom.xml @@ -13,7 +13,7 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.59.0 + 4.60.0-beta.1 Microsoft Azure SDK for SQL API of Azure Cosmos DB Service This Package contains Microsoft Azure Cosmos SDK (with Reactive Extension Reactor support) for Azure Cosmos DB SQL API jar @@ -65,12 +65,12 @@ Licensed under the MIT License. com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/GlobalEndpointManager.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/GlobalEndpointManager.java index 7dc27b329c8cd..3b4077ef76600 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/GlobalEndpointManager.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/GlobalEndpointManager.java @@ -303,7 +303,7 @@ private Mono startRefreshLocationTimerAsync(boolean initialization) { this::getDatabaseAccountAsync); return databaseAccountObs.flatMap(dbAccount -> { - logger.info("db account retrieved {}", databaseAccountObs); + logger.info("db account retrieved {}", dbAccount); this.refreshInBackground.set(false); return this.refreshLocationPrivateAsync(dbAccount); }); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java index 798e96353477c..bd054cd6822bf 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxGatewayStoreModel.java @@ -596,7 +596,7 @@ public Flux submitOpenConnectionTasksAndInitCaches(CosmosContainerProactiv @Override public void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider, Configs configs) { if (this.gatewayServerErrorInjector == null) { - this.gatewayServerErrorInjector = new GatewayServerErrorInjector(configs); + this.gatewayServerErrorInjector = new GatewayServerErrorInjector(configs, collectionCache, partitionKeyRangeCache); } this.gatewayServerErrorInjector.registerServerErrorInjector(injectorProvider.getServerErrorInjector()); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/faultinjection/GatewayServerErrorInjector.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/faultinjection/GatewayServerErrorInjector.java index 812d405ab5ffb..7c93bf31d04c5 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/faultinjection/GatewayServerErrorInjector.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/faultinjection/GatewayServerErrorInjector.java @@ -3,13 +3,22 @@ package com.azure.cosmos.implementation.faultinjection; +import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.CosmosException; import com.azure.cosmos.implementation.Configs; +import com.azure.cosmos.implementation.HttpConstants; +import com.azure.cosmos.implementation.PartitionKeyRange; +import com.azure.cosmos.implementation.ResourceType; import com.azure.cosmos.implementation.RxDocumentServiceRequest; import com.azure.cosmos.implementation.Utils; +import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; +import com.azure.cosmos.implementation.caches.RxCollectionCache; +import com.azure.cosmos.implementation.caches.RxPartitionKeyRangeCache; import com.azure.cosmos.implementation.http.HttpRequest; import com.azure.cosmos.implementation.http.HttpResponse; import com.azure.cosmos.implementation.http.ReactorNettyRequestRecord; +import com.azure.cosmos.implementation.routing.PartitionKeyInternal; +import com.azure.cosmos.implementation.routing.PartitionKeyInternalHelper; import io.netty.channel.ConnectTimeoutException; import io.netty.handler.timeout.ReadTimeoutException; import reactor.core.publisher.Mono; @@ -25,12 +34,23 @@ public class GatewayServerErrorInjector { private final Configs configs; + private final RxCollectionCache collectionCache; + private final RxPartitionKeyRangeCache partitionKeyRangeCache; private List faultInjectors = new ArrayList<>(); - public GatewayServerErrorInjector(Configs configs) { + public GatewayServerErrorInjector( + Configs configs, + RxCollectionCache collectionCache, + RxPartitionKeyRangeCache partitionKeyRangeCache) { checkNotNull(configs, "Argument 'configs' can not be null"); this.configs = configs; + this.collectionCache = collectionCache; + this.partitionKeyRangeCache = partitionKeyRangeCache; + } + + public GatewayServerErrorInjector(Configs configs) { + this(configs, null, null); } public void registerServerErrorInjector(IServerErrorInjector serverErrorInjector) { @@ -38,18 +58,74 @@ public void registerServerErrorInjector(IServerErrorInjector serverErrorInjector this.faultInjectors.add(serverErrorInjector); } + private Mono> resolvePartitionKeyRange(RxDocumentServiceRequest request) { + // faultInjection rule can be configured to only apply for a certain partition + // but in the normal flow, only session consistency will populate the resolvePartitionKey when apply session token + // so for other consistencies, we need to calculate here + if (request.getResourceType() != ResourceType.Document) { + return Mono.just(Utils.ValueHolder.initialize(null)); + } + + if (this.collectionCache == null || this.partitionKeyRangeCache == null) { + return Mono.just(Utils.ValueHolder.initialize(null)); + } + + if (request == null || request.requestContext == null) { + return Mono.just(Utils.ValueHolder.initialize(null)); + } + + if (request.requestContext.resolvedPartitionKeyRange != null) { + return Mono.just(Utils.ValueHolder.initialize(request.requestContext.resolvedPartitionKeyRange)); + } + + return this.collectionCache + .resolveCollectionAsync( + BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request) + .flatMap(collectionValueHolder -> { + return partitionKeyRangeCache + .tryLookupAsync( + BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), + collectionValueHolder.v.getResourceId(), + null, + null) + .flatMap(collectionRoutingMapValueHolder -> { + String partitionKeyRangeId = + request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); + PartitionKeyInternal partitionKeyInternal = request.getPartitionKeyInternal(); + if (StringUtils.isNotEmpty(partitionKeyRangeId)) { + PartitionKeyRange range = + collectionRoutingMapValueHolder.v.getRangeByPartitionKeyRangeId(partitionKeyRangeId); + request.requestContext.resolvedPartitionKeyRange = range; + } else if (partitionKeyInternal != null) { + String effectivePartitionKeyString = PartitionKeyInternalHelper + .getEffectivePartitionKeyString( + partitionKeyInternal, + collectionValueHolder.v.getPartitionKey()); + PartitionKeyRange range = + collectionRoutingMapValueHolder.v.getRangeByEffectivePartitionKey(effectivePartitionKeyString); + request.requestContext.resolvedPartitionKeyRange = range; + } + + return Mono.just(Utils.ValueHolder.initialize(request.requestContext.resolvedPartitionKeyRange)); + }); + }); + } + public Mono injectGatewayErrors( Duration responseTimeout, HttpRequest httpRequest, RxDocumentServiceRequest serviceRequest, Mono originalResponseMono) { - return injectGatewayErrors( - responseTimeout, - httpRequest, - serviceRequest, - originalResponseMono, - serviceRequest.requestContext.resolvedPartitionKeyRange != null - ? Arrays.asList(serviceRequest.requestContext.resolvedPartitionKeyRange.getId()) : null); + + return this.resolvePartitionKeyRange(serviceRequest) + .flatMap(resolvedPartitionKeyRangeValueHolder -> { + return injectGatewayErrors( + responseTimeout, + httpRequest, + serviceRequest, + originalResponseMono, + resolvedPartitionKeyRangeValueHolder.v == null ? null : Arrays.asList(resolvedPartitionKeyRangeValueHolder.v.getId())); + }); } public Mono injectGatewayErrors( diff --git a/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/pom.xml b/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/pom.xml index 2ab4fa2725b40..ed92db650b72b 100644 --- a/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/pom.xml +++ b/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/costmanagement/azure-resourcemanager-costmanagement/pom.xml b/sdk/costmanagement/azure-resourcemanager-costmanagement/pom.xml index 3ecfe2691dbbb..ccc94600045cc 100644 --- a/sdk/costmanagement/azure-resourcemanager-costmanagement/pom.xml +++ b/sdk/costmanagement/azure-resourcemanager-costmanagement/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/customerinsights/azure-resourcemanager-customerinsights/pom.xml b/sdk/customerinsights/azure-resourcemanager-customerinsights/pom.xml index e394d5d165a5a..6c354bf388a74 100644 --- a/sdk/customerinsights/azure-resourcemanager-customerinsights/pom.xml +++ b/sdk/customerinsights/azure-resourcemanager-customerinsights/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/dashboard/azure-resourcemanager-dashboard/pom.xml b/sdk/dashboard/azure-resourcemanager-dashboard/pom.xml index 6735682d909f7..d49f4a934a2ee 100644 --- a/sdk/dashboard/azure-resourcemanager-dashboard/pom.xml +++ b/sdk/dashboard/azure-resourcemanager-dashboard/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/databox/azure-resourcemanager-databox/pom.xml b/sdk/databox/azure-resourcemanager-databox/pom.xml index 6d0a6da6999e0..bef7e715dddd5 100644 --- a/sdk/databox/azure-resourcemanager-databox/pom.xml +++ b/sdk/databox/azure-resourcemanager-databox/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/databoxedge/azure-resourcemanager-databoxedge/pom.xml b/sdk/databoxedge/azure-resourcemanager-databoxedge/pom.xml index 90d7b619bd387..7baf6613244b0 100644 --- a/sdk/databoxedge/azure-resourcemanager-databoxedge/pom.xml +++ b/sdk/databoxedge/azure-resourcemanager-databoxedge/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/databricks/azure-resourcemanager-databricks/pom.xml b/sdk/databricks/azure-resourcemanager-databricks/pom.xml index f40c0ebe5526d..e05f2532449c2 100644 --- a/sdk/databricks/azure-resourcemanager-databricks/pom.xml +++ b/sdk/databricks/azure-resourcemanager-databricks/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/datadog/azure-resourcemanager-datadog/pom.xml b/sdk/datadog/azure-resourcemanager-datadog/pom.xml index bb8cac34177e3..8b729b7e8df09 100644 --- a/sdk/datadog/azure-resourcemanager-datadog/pom.xml +++ b/sdk/datadog/azure-resourcemanager-datadog/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/datafactory/azure-resourcemanager-datafactory/pom.xml b/sdk/datafactory/azure-resourcemanager-datafactory/pom.xml index f5ad35791d9bc..f803d66916df4 100644 --- a/sdk/datafactory/azure-resourcemanager-datafactory/pom.xml +++ b/sdk/datafactory/azure-resourcemanager-datafactory/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/pom.xml b/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/pom.xml index 8fcfa9344ee93..0f5766d53cfc8 100644 --- a/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/pom.xml +++ b/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/datalakestore/azure-resourcemanager-datalakestore/pom.xml b/sdk/datalakestore/azure-resourcemanager-datalakestore/pom.xml index 1293a651191d1..c357b7abcd4c8 100644 --- a/sdk/datalakestore/azure-resourcemanager-datalakestore/pom.xml +++ b/sdk/datalakestore/azure-resourcemanager-datalakestore/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/datamigration/azure-resourcemanager-datamigration/pom.xml b/sdk/datamigration/azure-resourcemanager-datamigration/pom.xml index 2d3b77943b48d..9e96a904842ee 100644 --- a/sdk/datamigration/azure-resourcemanager-datamigration/pom.xml +++ b/sdk/datamigration/azure-resourcemanager-datamigration/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/dataprotection/azure-resourcemanager-dataprotection/pom.xml b/sdk/dataprotection/azure-resourcemanager-dataprotection/pom.xml index 5234fe64164bb..a65a2470f2c1a 100644 --- a/sdk/dataprotection/azure-resourcemanager-dataprotection/pom.xml +++ b/sdk/dataprotection/azure-resourcemanager-dataprotection/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/defendereasm/azure-resourcemanager-defendereasm/pom.xml b/sdk/defendereasm/azure-resourcemanager-defendereasm/pom.xml index 0368e2132828e..e5ff561a5e282 100644 --- a/sdk/defendereasm/azure-resourcemanager-defendereasm/pom.xml +++ b/sdk/defendereasm/azure-resourcemanager-defendereasm/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/pom.xml b/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/pom.xml index ccd3ffd94af3d..10354a64efc8d 100644 --- a/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/pom.xml +++ b/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/pom.xml b/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/pom.xml index c33085a92982f..129e237a227e7 100644 --- a/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/pom.xml +++ b/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/pom.xml b/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/pom.xml index 6d73037a8ffe2..096cfe6bf1007 100644 --- a/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/pom.xml +++ b/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md b/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md index dad27d9444b16..86781c2f272ca 100644 --- a/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md +++ b/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md @@ -1,6 +1,16 @@ # Release History -## 1.0.0 (Unreleased) +## 1.1.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.0 (2024-04-30) This release targets Azure Dev Center 2023-04-01 General Available API, which is the same version as the previous 1.0.0-beta.3 release. The main improvement was the addition of models as Convenience API was enabled for the SDK. @@ -34,7 +44,6 @@ This release targets Azure Dev Center 2023-04-01 General Available API, which is - HibernateSupport - LocalAdministratorStatus - OsDisk - - package-info - PoolHealthStatus - PowerState - RemoteConnection @@ -50,7 +59,7 @@ This release targets Azure Dev Center 2023-04-01 General Available API, which is ### Breaking Changes -- Removed `filter` and `top` as optional request parameters. +- Removed `filter` and `top` as optional request parameters to match equivalent update in the API side. ## 1.0.0-beta.3 (2023-11-09) diff --git a/sdk/devcenter/azure-developer-devcenter/pom.xml b/sdk/devcenter/azure-developer-devcenter/pom.xml index edc298f81f1e0..070971ad964a2 100644 --- a/sdk/devcenter/azure-developer-devcenter/pom.xml +++ b/sdk/devcenter/azure-developer-devcenter/pom.xml @@ -9,7 +9,7 @@ com.azure azure-developer-devcenter - 1.0.0 + 1.1.0-beta.1 jar Microsoft Azure SDK for DevCenter Management @@ -43,12 +43,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -59,13 +59,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/devcenter/azure-resourcemanager-devcenter/pom.xml b/sdk/devcenter/azure-resourcemanager-devcenter/pom.xml index d74602633a98a..278a211e1f250 100644 --- a/sdk/devcenter/azure-resourcemanager-devcenter/pom.xml +++ b/sdk/devcenter/azure-resourcemanager-devcenter/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/devhub/azure-resourcemanager-devhub/pom.xml b/sdk/devhub/azure-resourcemanager-devhub/pom.xml index b30121b35bbb8..77064c55ef8f7 100644 --- a/sdk/devhub/azure-resourcemanager-devhub/pom.xml +++ b/sdk/devhub/azure-resourcemanager-devhub/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/pom.xml b/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/pom.xml index 2857f9515347e..49218f3e87d05 100644 --- a/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/pom.xml +++ b/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/pom.xml @@ -45,12 +45,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 org.junit.jupiter @@ -61,7 +61,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -73,7 +73,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/pom.xml b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/pom.xml index eec0d615ed871..b8c7cf2a23b43 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/pom.xml +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/pom.xml @@ -51,23 +51,23 @@ Code generated by Microsoft (R) TypeSpec Code Generator. com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/deviceupdate/azure-iot-deviceupdate/pom.xml b/sdk/deviceupdate/azure-iot-deviceupdate/pom.xml index 9847e8def47ad..9911bad91d562 100644 --- a/sdk/deviceupdate/azure-iot-deviceupdate/pom.xml +++ b/sdk/deviceupdate/azure-iot-deviceupdate/pom.xml @@ -39,23 +39,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/deviceupdate/azure-resourcemanager-deviceupdate/pom.xml b/sdk/deviceupdate/azure-resourcemanager-deviceupdate/pom.xml index 698d0ad587da8..a53b166637641 100644 --- a/sdk/deviceupdate/azure-resourcemanager-deviceupdate/pom.xml +++ b/sdk/deviceupdate/azure-resourcemanager-deviceupdate/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/devspaces/azure-resourcemanager-devspaces/pom.xml b/sdk/devspaces/azure-resourcemanager-devspaces/pom.xml index 7e018e3de93ed..ba41298f801be 100644 --- a/sdk/devspaces/azure-resourcemanager-devspaces/pom.xml +++ b/sdk/devspaces/azure-resourcemanager-devspaces/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/devtestlabs/azure-resourcemanager-devtestlabs/pom.xml b/sdk/devtestlabs/azure-resourcemanager-devtestlabs/pom.xml index 7e8d2f590de21..dd0fa150a56e5 100644 --- a/sdk/devtestlabs/azure-resourcemanager-devtestlabs/pom.xml +++ b/sdk/devtestlabs/azure-resourcemanager-devtestlabs/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/digitaltwins/azure-digitaltwins-core/pom.xml b/sdk/digitaltwins/azure-digitaltwins-core/pom.xml index ca1912a68560d..1a8d8cf3555e4 100644 --- a/sdk/digitaltwins/azure-digitaltwins-core/pom.xml +++ b/sdk/digitaltwins/azure-digitaltwins-core/pom.xml @@ -48,17 +48,17 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 com.fasterxml.jackson.core @@ -70,25 +70,25 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -160,7 +160,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 3009b8a4fcbf8..2cbbb0aad9f6f 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/digitaltwins/azure-resourcemanager-digitaltwins/pom.xml b/sdk/digitaltwins/azure-resourcemanager-digitaltwins/pom.xml index dfab516ab5316..0cb49f1342225 100644 --- a/sdk/digitaltwins/azure-resourcemanager-digitaltwins/pom.xml +++ b/sdk/digitaltwins/azure-resourcemanager-digitaltwins/pom.xml @@ -54,23 +54,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/dnsresolver/azure-resourcemanager-dnsresolver/pom.xml b/sdk/dnsresolver/azure-resourcemanager-dnsresolver/pom.xml index 633e419441d92..b021e1210c1bb 100644 --- a/sdk/dnsresolver/azure-resourcemanager-dnsresolver/pom.xml +++ b/sdk/dnsresolver/azure-resourcemanager-dnsresolver/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/documentintelligence/azure-ai-documentintelligence/README.md b/sdk/documentintelligence/azure-ai-documentintelligence/README.md index 5051206d0d097..0a31b9b47d7e2 100644 --- a/sdk/documentintelligence/azure-ai-documentintelligence/README.md +++ b/sdk/documentintelligence/azure-ai-documentintelligence/README.md @@ -90,7 +90,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/documentintelligence/azure-ai-documentintelligence/pom.xml b/sdk/documentintelligence/azure-ai-documentintelligence/pom.xml index 4abbe56f489b4..ac1f2f2f12e57 100644 --- a/sdk/documentintelligence/azure-ai-documentintelligence/pom.xml +++ b/sdk/documentintelligence/azure-ai-documentintelligence/pom.xml @@ -47,12 +47,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.slf4j @@ -65,19 +65,19 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -101,7 +101,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -116,7 +116,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/dynatrace/azure-resourcemanager-dynatrace/pom.xml b/sdk/dynatrace/azure-resourcemanager-dynatrace/pom.xml index 1f50332a33c48..10d5303be6bce 100644 --- a/sdk/dynatrace/azure-resourcemanager-dynatrace/pom.xml +++ b/sdk/dynatrace/azure-resourcemanager-dynatrace/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/e2e/pom.xml b/sdk/e2e/pom.xml index f3fc4c3a191c3..a685a954f5a99 100644 --- a/sdk/e2e/pom.xml +++ b/sdk/e2e/pom.xml @@ -29,12 +29,12 @@ com.azure azure-core - 1.49.0-beta.1 + 1.50.0-beta.1 com.azure azure-core-http-netty - 1.15.0-beta.1 + 1.16.0-beta.1 com.azure @@ -70,7 +70,7 @@ com.azure azure-core-test - 1.25.0-beta.1 + 1.26.0-beta.1 test diff --git a/sdk/easm/azure-analytics-defender-easm/pom.xml b/sdk/easm/azure-analytics-defender-easm/pom.xml index 83547a4ed28e3..112ba3d517d5d 100644 --- a/sdk/easm/azure-analytics-defender-easm/pom.xml +++ b/sdk/easm/azure-analytics-defender-easm/pom.xml @@ -48,12 +48,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -90,13 +90,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/edgeorder/azure-resourcemanager-edgeorder/pom.xml b/sdk/edgeorder/azure-resourcemanager-edgeorder/pom.xml index ea0b311d23471..eb5e53652ea34 100644 --- a/sdk/edgeorder/azure-resourcemanager-edgeorder/pom.xml +++ b/sdk/edgeorder/azure-resourcemanager-edgeorder/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/edgezones/azure-resourcemanager-edgezones/pom.xml b/sdk/edgezones/azure-resourcemanager-edgezones/pom.xml index 5e9c9a6eee6c5..9b0f6e2ca74a0 100644 --- a/sdk/edgezones/azure-resourcemanager-edgezones/pom.xml +++ b/sdk/edgezones/azure-resourcemanager-edgezones/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/education/azure-resourcemanager-education/pom.xml b/sdk/education/azure-resourcemanager-education/pom.xml index 120dd5c27b80d..04d8278d4800b 100644 --- a/sdk/education/azure-resourcemanager-education/pom.xml +++ b/sdk/education/azure-resourcemanager-education/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/elastic/azure-resourcemanager-elastic/pom.xml b/sdk/elastic/azure-resourcemanager-elastic/pom.xml index 4052ea835fe30..30a7450ebd0e9 100644 --- a/sdk/elastic/azure-resourcemanager-elastic/pom.xml +++ b/sdk/elastic/azure-resourcemanager-elastic/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/elasticsan/azure-resourcemanager-elasticsan/pom.xml b/sdk/elasticsan/azure-resourcemanager-elasticsan/pom.xml index fa555cd787c46..8681d41b02060 100644 --- a/sdk/elasticsan/azure-resourcemanager-elasticsan/pom.xml +++ b/sdk/elasticsan/azure-resourcemanager-elasticsan/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml b/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml index d16878c23653b..5d13cb1a4e764 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml +++ b/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml @@ -83,7 +83,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -118,7 +118,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml b/sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml index c0ffe5cd09220..da3775d7374b7 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml +++ b/sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml @@ -48,12 +48,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -70,13 +70,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/eventgrid/azure-messaging-eventgrid/pom.xml b/sdk/eventgrid/azure-messaging-eventgrid/pom.xml index f169b97999855..2cecbe06c200e 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/pom.xml +++ b/sdk/eventgrid/azure-messaging-eventgrid/pom.xml @@ -72,7 +72,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -82,14 +82,14 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 test @@ -101,7 +101,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -125,7 +125,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/eventgrid/azure-resourcemanager-eventgrid/pom.xml b/sdk/eventgrid/azure-resourcemanager-eventgrid/pom.xml index 62d66c18aacfd..31fb652e37c27 100644 --- a/sdk/eventgrid/azure-resourcemanager-eventgrid/pom.xml +++ b/sdk/eventgrid/azure-resourcemanager-eventgrid/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml index bbd71c5e68df7..e02a8d8a36783 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml @@ -61,13 +61,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/pom.xml index e06dd6056191f..78befa6ea0e66 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/pom.xml @@ -53,7 +53,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/eventhubs/azure-messaging-eventhubs-stress/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs-stress/pom.xml index 4a55b0fe21cf2..05f389908badf 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-stress/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs-stress/pom.xml @@ -65,12 +65,12 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 com.azure azure-core-metrics-opentelemetry - 1.0.0-beta.18 + 1.0.0-beta.19 diff --git a/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/pom.xml index f59807386fb8c..ff48744e25760 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/pom.xml @@ -45,7 +45,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 diff --git a/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/src/main/java/com/azure/messaging/eventhubs/perf/ReactorReceiveEventsTest.java b/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/src/main/java/com/azure/messaging/eventhubs/perf/ReactorReceiveEventsTest.java index 15f8d719eadaf..49a82961dc8fe 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/src/main/java/com/azure/messaging/eventhubs/perf/ReactorReceiveEventsTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/src/main/java/com/azure/messaging/eventhubs/perf/ReactorReceiveEventsTest.java @@ -90,7 +90,7 @@ public Mono setupAsync() { connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); final ReactorProvider provider = new ReactorProvider(); - final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); + final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider, null); final AmqpLinkProvider linkProvider = new AmqpLinkProvider(); final PerfMessageSerializer messageSerializer = new PerfMessageSerializer(); connection = new ReactorConnection(connectionId, diff --git a/sdk/eventhubs/azure-messaging-eventhubs/README.md b/sdk/eventhubs/azure-messaging-eventhubs/README.md index 1f19b14ccdc84..c2ad1c9ad750e 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/README.md +++ b/sdk/eventhubs/azure-messaging-eventhubs/README.md @@ -137,7 +137,7 @@ platform. First, add the package: com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/eventhubs/azure-messaging-eventhubs/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs/pom.xml index 58792675f1555..031f1d57c31f2 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs/pom.xml @@ -44,25 +44,25 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-amqp - 2.10.0-beta.1 + 2.9.4 com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -114,7 +114,7 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 test @@ -142,7 +142,7 @@ com.azure azure-core-experimental - 1.0.0-beta.49 + 1.0.0-beta.50 test 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 c50f9d4b94a6d..86101a67af935 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 5ea403598f74a..f7714375106cc 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 33de24fb11ff2..d117c200ee0d5 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 8b9bdaa665ebd..06a1e658e7e76 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 2843c5f92bd9e..2145926309665 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 bc8d559f26c51..8943cbb8204aa 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 6399a399f8e35..467b2a27e7033 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 5f106e6fbd02e..40acadca38c1a 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 @@ -10,21 +10,21 @@ import com.azure.core.amqp.implementation.ConnectionStringProperties; import com.azure.core.experimental.util.tracing.LoggingTracerProvider; import com.azure.core.test.TestBase; +import com.azure.core.test.TestContextManager; import com.azure.core.test.TestMode; import com.azure.core.util.ClientOptions; 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; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.TestInfo; import org.mockito.Mockito; import reactor.core.Disposable; import reactor.core.scheduler.Scheduler; @@ -60,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; @@ -103,10 +105,12 @@ public static void afterAll() { } @BeforeEach - public void setupTest(TestInfo testInfo) { - System.out.printf("----- [%s]: Performing integration test set-up. -----%n", testInfo.getDisplayName()); + @Override + public void setupTest(TestContextManager testContextManager) { + logger.info("----- {}: Performing integration test set-up. -----", + testContextManager.getTestPlaybackRecordingName()); - testName = testInfo.getDisplayName(); + testName = testContextManager.getTrackerTestName(); skipIfNotRecordMode(); toClose = new ArrayList<>(); beforeTest(); @@ -124,9 +128,8 @@ protected Disposable toClose(Disposable closeable) { // These are overridden because we don't use the Interceptor Manager. @Override - @AfterEach - public void teardownTest(TestInfo testInfo) { - System.out.printf("----- [%s]: Performing test clean-up. -----%n", testInfo.getDisplayName()); + public void teardownTest() { + logger.info("----- {}: Performing test clean-up. -----", testName); afterTest(); logger.info("Disposing of subscriptions, consumers and clients."); @@ -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; @@ -302,7 +305,7 @@ protected synchronized Map getTestData() { return testEventData; } - System.out.println("--> Adding events to Event Hubs."); + logger.info("--> Adding events to Event Hubs."); final Map integrationData = new HashMap<>(); try (EventHubProducerClient producer = new EventHubClientBuilder() @@ -312,7 +315,7 @@ protected synchronized Map getTestData() { .buildProducerClient()) { producer.getPartitionIds().forEach(partitionId -> { - System.out.printf("--> Adding events to partition: %s%n", partitionId); + logger.info("--> Adding events to partition: " + partitionId); final PartitionProperties partitionProperties = producer.getPartitionProperties(partitionId); final String messageId = UUID.randomUUID().toString(); final int numberOfEvents = 15; @@ -326,7 +329,7 @@ protected synchronized Map getTestData() { }); if (integrationData.size() != NUMBER_OF_PARTITIONS) { - System.out.printf("--> WARNING: Number of partitions is different. Expected: %s. Actual %s%n", + logger.warning("--> WARNING: Number of partitions is different. Expected: {}. Actual {}", NUMBER_OF_PARTITIONS, integrationData.size()); } 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 79e8dc03672ca..d1b6c899d2973 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 1fa96bf7fdc94..5d277e3661329 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 9562eac39f4e8..c43bebc11c500 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 c731b8bea014a..b7acff2826e5b 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/extendedlocation/azure-resourcemanager-extendedlocation/pom.xml b/sdk/extendedlocation/azure-resourcemanager-extendedlocation/pom.xml index 5f468a9c629d0..f090a0669be0c 100644 --- a/sdk/extendedlocation/azure-resourcemanager-extendedlocation/pom.xml +++ b/sdk/extendedlocation/azure-resourcemanager-extendedlocation/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/face/azure-ai-vision-face/src/test/java/com/azure/ai/vision/face/tests/DetectionTest.java b/sdk/face/azure-ai-vision-face/src/test/java/com/azure/ai/vision/face/tests/DetectionTest.java index dd764aef22278..2dadff3bff6a0 100755 --- a/sdk/face/azure-ai-vision-face/src/test/java/com/azure/ai/vision/face/tests/DetectionTest.java +++ b/sdk/face/azure-ai-vision-face/src/test/java/com/azure/ai/vision/face/tests/DetectionTest.java @@ -5,7 +5,6 @@ import com.azure.ai.vision.face.FaceAsyncClient; import com.azure.ai.vision.face.FaceClient; -import com.azure.ai.vision.face.FaceServiceVersion; import com.azure.ai.vision.face.models.FaceDetectionModel; import com.azure.ai.vision.face.models.FaceDetectionResult; import com.azure.ai.vision.face.models.FaceRecognitionModel; @@ -14,7 +13,6 @@ import com.azure.ai.vision.face.tests.commands.detection.DetectSyncFunction; import com.azure.ai.vision.face.tests.utils.FaceDisplayNameGenerator; import com.azure.ai.vision.face.tests.utils.TestUtils; -import com.azure.core.http.HttpClient; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayNameGeneration; diff --git a/sdk/fluidrelay/azure-resourcemanager-fluidrelay/pom.xml b/sdk/fluidrelay/azure-resourcemanager-fluidrelay/pom.xml index 08b16a822c5a1..56eede15cc84c 100644 --- a/sdk/fluidrelay/azure-resourcemanager-fluidrelay/pom.xml +++ b/sdk/fluidrelay/azure-resourcemanager-fluidrelay/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure.resourcemanager @@ -60,13 +60,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/formrecognizer/azure-ai-formrecognizer-perf/pom.xml b/sdk/formrecognizer/azure-ai-formrecognizer-perf/pom.xml index 06e06cc77ab9a..62752492073db 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer-perf/pom.xml +++ b/sdk/formrecognizer/azure-ai-formrecognizer-perf/pom.xml @@ -36,12 +36,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -105,7 +105,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/README.md b/sdk/formrecognizer/azure-ai-formrecognizer/README.md index 1943095524b9f..81253a51b3fa2 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/README.md +++ b/sdk/formrecognizer/azure-ai-formrecognizer/README.md @@ -167,7 +167,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/pom.xml b/sdk/formrecognizer/azure-ai-formrecognizer/pom.xml index cef83ed062745..dea2055b12dc9 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/pom.xml +++ b/sdk/formrecognizer/azure-ai-formrecognizer/pom.xml @@ -52,31 +52,31 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -100,7 +100,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -115,7 +115,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/frontdoor/azure-resourcemanager-frontdoor/pom.xml b/sdk/frontdoor/azure-resourcemanager-frontdoor/pom.xml index c86f8c9e9da49..395deda047a24 100644 --- a/sdk/frontdoor/azure-resourcemanager-frontdoor/pom.xml +++ b/sdk/frontdoor/azure-resourcemanager-frontdoor/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/graphservices/azure-resourcemanager-graphservices/pom.xml b/sdk/graphservices/azure-resourcemanager-graphservices/pom.xml index dd7e65e8a555b..ac12aed100a15 100644 --- a/sdk/graphservices/azure-resourcemanager-graphservices/pom.xml +++ b/sdk/graphservices/azure-resourcemanager-graphservices/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/hanaonazure/azure-resourcemanager-hanaonazure/pom.xml b/sdk/hanaonazure/azure-resourcemanager-hanaonazure/pom.xml index b17c0d388421d..6e598e13f97fd 100644 --- a/sdk/hanaonazure/azure-resourcemanager-hanaonazure/pom.xml +++ b/sdk/hanaonazure/azure-resourcemanager-hanaonazure/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/pom.xml b/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/pom.xml index 1bfea5c248d0a..2a05de57cc95c 100644 --- a/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/pom.xml +++ b/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/pom.xml b/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/pom.xml index 1c0fa199c8a49..4b6b750f3e4fb 100644 --- a/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/pom.xml +++ b/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/hdinsight/azure-resourcemanager-hdinsight/pom.xml b/sdk/hdinsight/azure-resourcemanager-hdinsight/pom.xml index 39da8f78db347..e5ba1331b7365 100644 --- a/sdk/hdinsight/azure-resourcemanager-hdinsight/pom.xml +++ b/sdk/hdinsight/azure-resourcemanager-hdinsight/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/healthbot/azure-resourcemanager-healthbot/pom.xml b/sdk/healthbot/azure-resourcemanager-healthbot/pom.xml index ee09a75af017b..c3717fb7bfa1c 100644 --- a/sdk/healthbot/azure-resourcemanager-healthbot/pom.xml +++ b/sdk/healthbot/azure-resourcemanager-healthbot/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/healthcareapis/azure-resourcemanager-healthcareapis/pom.xml b/sdk/healthcareapis/azure-resourcemanager-healthcareapis/pom.xml index 19a6dc562dd4e..795d067040a4c 100644 --- a/sdk/healthcareapis/azure-resourcemanager-healthcareapis/pom.xml +++ b/sdk/healthcareapis/azure-resourcemanager-healthcareapis/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/healthinsights/azure-health-insights-cancerprofiling/pom.xml b/sdk/healthinsights/azure-health-insights-cancerprofiling/pom.xml index 303754f5b14bd..394e8517ddc9c 100644 --- a/sdk/healthinsights/azure-health-insights-cancerprofiling/pom.xml +++ b/sdk/healthinsights/azure-health-insights-cancerprofiling/pom.xml @@ -52,12 +52,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -74,13 +74,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/healthinsights/azure-health-insights-clinicalmatching/pom.xml b/sdk/healthinsights/azure-health-insights-clinicalmatching/pom.xml index 6de4b045c7420..5337ff430cd0a 100644 --- a/sdk/healthinsights/azure-health-insights-clinicalmatching/pom.xml +++ b/sdk/healthinsights/azure-health-insights-clinicalmatching/pom.xml @@ -52,12 +52,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -74,13 +74,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md b/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md index 13782c80c1163..bb5249bfbb72f 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/healthinsights/azure-health-insights-radiologyinsights/pom.xml b/sdk/healthinsights/azure-health-insights-radiologyinsights/pom.xml index 8f95d6cd136a0..fd1d0be13c94d 100644 --- a/sdk/healthinsights/azure-health-insights-radiologyinsights/pom.xml +++ b/sdk/healthinsights/azure-health-insights-radiologyinsights/pom.xml @@ -50,12 +50,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -78,13 +78,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -96,7 +96,7 @@ com.azure azure-core-experimental - 1.0.0-beta.49 + 1.0.0-beta.50 diff --git a/sdk/hybridcompute/azure-resourcemanager-hybridcompute/pom.xml b/sdk/hybridcompute/azure-resourcemanager-hybridcompute/pom.xml index e277f7ec5957c..956615575002a 100644 --- a/sdk/hybridcompute/azure-resourcemanager-hybridcompute/pom.xml +++ b/sdk/hybridcompute/azure-resourcemanager-hybridcompute/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/pom.xml b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/pom.xml index fa9f67b444441..2ba7090790552 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/pom.xml +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/pom.xml b/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/pom.xml index a5664e21374ac..d62191bd7b864 100644 --- a/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/pom.xml +++ b/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/pom.xml b/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/pom.xml index ceb23bb7a5a5f..148318ef91b44 100644 --- a/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/pom.xml +++ b/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/pom.xml b/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/pom.xml index a413071efc3a3..ddfb427537432 100644 --- a/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/pom.xml +++ b/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/identity/azure-identity-broker/CHANGELOG.md b/sdk/identity/azure-identity-broker/CHANGELOG.md index 229b0eec42549..47e72455d4374 100644 --- a/sdk/identity/azure-identity-broker/CHANGELOG.md +++ b/sdk/identity/azure-identity-broker/CHANGELOG.md @@ -10,6 +10,14 @@ ### Other Changes +## 1.1.1 (2024-05-02) + +### Other Changes + +#### Dependency Updates +- +- Upgraded `azure-identity` from `1.12.0` to version `1.12.1`. + ## 1.1.0 (2024-04-08) ### Features Added diff --git a/sdk/identity/azure-identity-broker/README.md b/sdk/identity/azure-identity-broker/README.md index 1ab5a19d332f6..6705e6905062d 100644 --- a/sdk/identity/azure-identity-broker/README.md +++ b/sdk/identity/azure-identity-broker/README.md @@ -46,7 +46,7 @@ To take dependency on a particular version of the library that isn't present in com.azure azure-identity-broker - 1.0.4 + 1.1.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/identity/azure-identity-extensions/pom.xml b/sdk/identity/azure-identity-extensions/pom.xml index 70fcceab73c85..63548790a343e 100644 --- a/sdk/identity/azure-identity-extensions/pom.xml +++ b/sdk/identity/azure-identity-extensions/pom.xml @@ -34,7 +34,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 diff --git a/sdk/identity/azure-identity-perf/pom.xml b/sdk/identity/azure-identity-perf/pom.xml index 54f9e4c793370..a1fd319787048 100644 --- a/sdk/identity/azure-identity-perf/pom.xml +++ b/sdk/identity/azure-identity-perf/pom.xml @@ -36,12 +36,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 15beaa9876536..4f6a9036f3d00 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -10,6 +10,14 @@ ### Other Changes +## 1.12.1 (2024-05-02) + +### Other Changes + +#### 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`. + ## 1.12.0 (2024-04-08) ### Features Added diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md index 85a2e8b6f6248..c7333c8e8f442 100644 --- a/sdk/identity/azure-identity/README.md +++ b/sdk/identity/azure-identity/README.md @@ -46,7 +46,7 @@ To take dependency on a particular version of the library that isn't present in com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/identity/azure-identity/pom.xml b/sdk/identity/azure-identity/pom.xml index 7e2bf61b67499..973bcff00872a 100644 --- a/sdk/identity/azure-identity/pom.xml +++ b/sdk/identity/azure-identity/pom.xml @@ -31,12 +31,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -56,7 +56,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/imagebuilder/azure-resourcemanager-imagebuilder/pom.xml b/sdk/imagebuilder/azure-resourcemanager-imagebuilder/pom.xml index dfd2621ecd38b..6369a7f16bca0 100644 --- a/sdk/imagebuilder/azure-resourcemanager-imagebuilder/pom.xml +++ b/sdk/imagebuilder/azure-resourcemanager-imagebuilder/pom.xml @@ -50,17 +50,17 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -78,7 +78,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/iotcentral/azure-resourcemanager-iotcentral/pom.xml b/sdk/iotcentral/azure-resourcemanager-iotcentral/pom.xml index 5771c40cc0336..fe5b69c7ad427 100644 --- a/sdk/iotcentral/azure-resourcemanager-iotcentral/pom.xml +++ b/sdk/iotcentral/azure-resourcemanager-iotcentral/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure.resourcemanager @@ -60,13 +60,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/pom.xml b/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/pom.xml index c9c8ba1ec864b..4b04a4724aa65 100644 --- a/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/pom.xml +++ b/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/iothub/azure-resourcemanager-iothub/pom.xml b/sdk/iothub/azure-resourcemanager-iothub/pom.xml index 379aa513ed5db..f45e88c9c584b 100644 --- a/sdk/iothub/azure-resourcemanager-iothub/pom.xml +++ b/sdk/iothub/azure-resourcemanager-iothub/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md index bbfeb98fc619a..9812be10c3461 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md @@ -10,6 +10,11 @@ ### Other Changes +## 4.5.3 (2024-04-30) + +### Other Changes + +- No changes but only upgrade version to fix Microsoft Doc. ## 4.5.2 (2024-04-23) diff --git a/sdk/keyvault/azure-security-keyvault-administration/pom.xml b/sdk/keyvault/azure-security-keyvault-administration/pom.xml index f4e7303323457..2358a7694e43a 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-administration/pom.xml @@ -48,7 +48,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -58,7 +58,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -94,19 +94,19 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -124,7 +124,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -139,7 +139,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/keyvault/azure-security-keyvault-certificates/pom.xml b/sdk/keyvault/azure-security-keyvault-certificates/pom.xml index 1de15ab61437f..92d1b55f22878 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-certificates/pom.xml @@ -47,7 +47,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -58,7 +58,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -89,25 +89,25 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -155,7 +155,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 176841ed1efaf..393a22f5e03f8 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-jca/pom.xml b/sdk/keyvault/azure-security-keyvault-jca/pom.xml index 80917369c595d..68ab361147190 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-jca/pom.xml @@ -86,7 +86,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 test diff --git a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md index 1918d1ec86f07..886a644f33084 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md @@ -10,6 +10,12 @@ ### Other Changes +## 4.8.3 (2024-04-30) + +### Other Changes + +- No changes but only upgrade version to fix Microsoft Doc. + ## 4.8.2 (2024-04-09) ### Bugs Fixed diff --git a/sdk/keyvault/azure-security-keyvault-keys/pom.xml b/sdk/keyvault/azure-security-keyvault-keys/pom.xml index ccf90146e3d86..73076bb9428b5 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-keys/pom.xml @@ -50,7 +50,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 @@ -62,7 +62,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -93,25 +93,25 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -140,7 +140,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 3012b65ad5d21..3cb7feb45efa7 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 10ace970322b4..ae77209705b3a 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 419c079e7854f..01e37bb6cdac5 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 91e7ed3f2276a..3aecf85da493b 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-perf/pom.xml b/sdk/keyvault/azure-security-keyvault-perf/pom.xml index 3421ea82fd2bf..c6d05ddbf2cdb 100644 --- a/sdk/keyvault/azure-security-keyvault-perf/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-perf/pom.xml @@ -41,12 +41,12 @@ com.azure azure-identity - 1.12.0 + 1.12.1 com.azure azure-core-test - 1.24.2 + 1.25.0 com.azure @@ -57,12 +57,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -126,7 +126,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 diff --git a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml b/sdk/keyvault/azure-security-keyvault-secrets/pom.xml index 9e3ec2acae672..b385dc052e3b3 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-secrets/pom.xml @@ -46,7 +46,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 @@ -58,20 +58,20 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -109,14 +109,14 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -131,7 +131,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 155f022e979af..63fffc5dffbe5 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 0e8309f0b9ce9..4e43e1a38cb8e 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/azure-security-test-keyvault-jca/pom.xml b/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml index fefc45eb308cb..016f683c6b297 100644 --- a/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml +++ b/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml @@ -82,7 +82,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/pom.xml b/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/pom.xml index 3a59c9e6d37eb..df2697d113a0f 100644 --- a/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/pom.xml +++ b/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/kusto/azure-resourcemanager-kusto/pom.xml b/sdk/kusto/azure-resourcemanager-kusto/pom.xml index 4f3091da7686d..d9029116c3e6c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/pom.xml +++ b/sdk/kusto/azure-resourcemanager-kusto/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/labservices/azure-resourcemanager-labservices/pom.xml b/sdk/labservices/azure-resourcemanager-labservices/pom.xml index 9b95608409f20..6fc37018dd2f5 100644 --- a/sdk/labservices/azure-resourcemanager-labservices/pom.xml +++ b/sdk/labservices/azure-resourcemanager-labservices/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/largeinstance/azure-resourcemanager-largeinstance/pom.xml b/sdk/largeinstance/azure-resourcemanager-largeinstance/pom.xml index 3dac3bb7d9ab7..fb6975f4e0415 100644 --- a/sdk/largeinstance/azure-resourcemanager-largeinstance/pom.xml +++ b/sdk/largeinstance/azure-resourcemanager-largeinstance/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/loadtesting/azure-developer-loadtesting/pom.xml b/sdk/loadtesting/azure-developer-loadtesting/pom.xml index f24030b6d0ca8..df3c48e460d83 100644 --- a/sdk/loadtesting/azure-developer-loadtesting/pom.xml +++ b/sdk/loadtesting/azure-developer-loadtesting/pom.xml @@ -43,12 +43,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -59,13 +59,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/loadtesting/azure-resourcemanager-loadtesting/pom.xml b/sdk/loadtesting/azure-resourcemanager-loadtesting/pom.xml index 7e1bf72f905b4..19883aadf3a1a 100644 --- a/sdk/loadtesting/azure-resourcemanager-loadtesting/pom.xml +++ b/sdk/loadtesting/azure-resourcemanager-loadtesting/pom.xml @@ -45,23 +45,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/loganalytics/azure-resourcemanager-loganalytics/pom.xml b/sdk/loganalytics/azure-resourcemanager-loganalytics/pom.xml index de929c52bc73c..5631069ebd22f 100644 --- a/sdk/loganalytics/azure-resourcemanager-loganalytics/pom.xml +++ b/sdk/loganalytics/azure-resourcemanager-loganalytics/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/loganalytics/microsoft-azure-loganalytics/pom.xml b/sdk/loganalytics/microsoft-azure-loganalytics/pom.xml index 1c51726287e1a..428e1e32bae25 100644 --- a/sdk/loganalytics/microsoft-azure-loganalytics/pom.xml +++ b/sdk/loganalytics/microsoft-azure-loganalytics/pom.xml @@ -75,7 +75,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/logic/azure-resourcemanager-logic/pom.xml b/sdk/logic/azure-resourcemanager-logic/pom.xml index ecb729e162986..1235a60fb3b25 100644 --- a/sdk/logic/azure-resourcemanager-logic/pom.xml +++ b/sdk/logic/azure-resourcemanager-logic/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/logz/azure-resourcemanager-logz/pom.xml b/sdk/logz/azure-resourcemanager-logz/pom.xml index 30d27c5aa2f6f..15df8012fa529 100644 --- a/sdk/logz/azure-resourcemanager-logz/pom.xml +++ b/sdk/logz/azure-resourcemanager-logz/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/machinelearning/azure-resourcemanager-machinelearning/pom.xml b/sdk/machinelearning/azure-resourcemanager-machinelearning/pom.xml index 1b0f634acbd27..135ecd7536524 100644 --- a/sdk/machinelearning/azure-resourcemanager-machinelearning/pom.xml +++ b/sdk/machinelearning/azure-resourcemanager-machinelearning/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure.resourcemanager @@ -78,13 +78,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/machinelearningservices/azure-resourcemanager-machinelearningservices/pom.xml b/sdk/machinelearningservices/azure-resourcemanager-machinelearningservices/pom.xml index ac3edd41e63b5..b8f75794700c8 100644 --- a/sdk/machinelearningservices/azure-resourcemanager-machinelearningservices/pom.xml +++ b/sdk/machinelearningservices/azure-resourcemanager-machinelearningservices/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/maintenance/azure-resourcemanager-maintenance/pom.xml b/sdk/maintenance/azure-resourcemanager-maintenance/pom.xml index ae141b087774d..5e18339ed8d78 100644 --- a/sdk/maintenance/azure-resourcemanager-maintenance/pom.xml +++ b/sdk/maintenance/azure-resourcemanager-maintenance/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/managedapplications/azure-resourcemanager-managedapplications/pom.xml b/sdk/managedapplications/azure-resourcemanager-managedapplications/pom.xml index b24b8007e59ec..7022e9dc67be3 100644 --- a/sdk/managedapplications/azure-resourcemanager-managedapplications/pom.xml +++ b/sdk/managedapplications/azure-resourcemanager-managedapplications/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/pom.xml b/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/pom.xml index ecd466143413a..a5381a40236fc 100644 --- a/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/pom.xml +++ b/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/managementgroups/azure-resourcemanager-managementgroups/pom.xml b/sdk/managementgroups/azure-resourcemanager-managementgroups/pom.xml index a55907c4fe3d7..7cbbef840df39 100644 --- a/sdk/managementgroups/azure-resourcemanager-managementgroups/pom.xml +++ b/sdk/managementgroups/azure-resourcemanager-managementgroups/pom.xml @@ -53,23 +53,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/maps/azure-maps-elevation/pom.xml b/sdk/maps/azure-maps-elevation/pom.xml index 99e5af1ff6a8e..656e9faec5c49 100644 --- a/sdk/maps/azure-maps-elevation/pom.xml +++ b/sdk/maps/azure-maps-elevation/pom.xml @@ -51,35 +51,35 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -118,7 +118,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/maps/azure-maps-geolocation/pom.xml b/sdk/maps/azure-maps-geolocation/pom.xml index 6d657c53dfb52..307153389c17c 100644 --- a/sdk/maps/azure-maps-geolocation/pom.xml +++ b/sdk/maps/azure-maps-geolocation/pom.xml @@ -55,35 +55,35 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -122,7 +122,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/maps/azure-maps-render/pom.xml b/sdk/maps/azure-maps-render/pom.xml index a8520f3d1e597..880502be161fd 100644 --- a/sdk/maps/azure-maps-render/pom.xml +++ b/sdk/maps/azure-maps-render/pom.xml @@ -64,35 +64,35 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -131,7 +131,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/maps/azure-maps-route/pom.xml b/sdk/maps/azure-maps-route/pom.xml index e229bd7e1af23..79ddc49533a37 100644 --- a/sdk/maps/azure-maps-route/pom.xml +++ b/sdk/maps/azure-maps-route/pom.xml @@ -63,36 +63,36 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -137,7 +137,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/maps/azure-maps-search/pom.xml b/sdk/maps/azure-maps-search/pom.xml index b1d4dcba17a72..8a544a3a92e06 100644 --- a/sdk/maps/azure-maps-search/pom.xml +++ b/sdk/maps/azure-maps-search/pom.xml @@ -65,35 +65,35 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -132,7 +132,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/maps/azure-maps-timezone/pom.xml b/sdk/maps/azure-maps-timezone/pom.xml index 2f210bc6bc877..c820ce8b4b953 100644 --- a/sdk/maps/azure-maps-timezone/pom.xml +++ b/sdk/maps/azure-maps-timezone/pom.xml @@ -61,35 +61,35 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -128,7 +128,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/maps/azure-maps-traffic/pom.xml b/sdk/maps/azure-maps-traffic/pom.xml index dfd14f3e55a44..357df211fb519 100644 --- a/sdk/maps/azure-maps-traffic/pom.xml +++ b/sdk/maps/azure-maps-traffic/pom.xml @@ -52,35 +52,35 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -119,7 +119,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/maps/azure-maps-weather/pom.xml b/sdk/maps/azure-maps-weather/pom.xml index a6b82b5a4b961..21341c4c85e25 100644 --- a/sdk/maps/azure-maps-weather/pom.xml +++ b/sdk/maps/azure-maps-weather/pom.xml @@ -62,35 +62,35 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -129,7 +129,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/maps/azure-resourcemanager-maps/pom.xml b/sdk/maps/azure-resourcemanager-maps/pom.xml index 9e2845c6b292f..9f05a1aa34b08 100644 --- a/sdk/maps/azure-resourcemanager-maps/pom.xml +++ b/sdk/maps/azure-resourcemanager-maps/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/mariadb/azure-resourcemanager-mariadb/pom.xml b/sdk/mariadb/azure-resourcemanager-mariadb/pom.xml index 0c435a5c41c2b..4d48e2e799168 100644 --- a/sdk/mariadb/azure-resourcemanager-mariadb/pom.xml +++ b/sdk/mariadb/azure-resourcemanager-mariadb/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/pom.xml b/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/pom.xml index 74c9c7bc7df99..fdbc1edb5e411 100644 --- a/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/pom.xml +++ b/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/mediaservices/azure-resourcemanager-mediaservices/pom.xml b/sdk/mediaservices/azure-resourcemanager-mediaservices/pom.xml index 5364afd9b4d87..455663d13ce12 100644 --- a/sdk/mediaservices/azure-resourcemanager-mediaservices/pom.xml +++ b/sdk/mediaservices/azure-resourcemanager-mediaservices/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/pom.xml b/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/pom.xml index 2218644750462..dec4e3ab909b4 100644 --- a/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/pom.xml +++ b/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/pom.xml @@ -35,12 +35,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/metricsadvisor/azure-ai-metricsadvisor/README.md b/sdk/metricsadvisor/azure-ai-metricsadvisor/README.md index fcd9859501369..71b797c9cde7c 100644 --- a/sdk/metricsadvisor/azure-ai-metricsadvisor/README.md +++ b/sdk/metricsadvisor/azure-ai-metricsadvisor/README.md @@ -112,7 +112,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/metricsadvisor/azure-ai-metricsadvisor/pom.xml b/sdk/metricsadvisor/azure-ai-metricsadvisor/pom.xml index 9feb53f48e222..692aa61b4ef67 100644 --- a/sdk/metricsadvisor/azure-ai-metricsadvisor/pom.xml +++ b/sdk/metricsadvisor/azure-ai-metricsadvisor/pom.xml @@ -45,12 +45,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -62,19 +62,19 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -98,7 +98,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -113,7 +113,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/pom.xml b/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/pom.xml index 782817ca4c9f2..0840ead6d6c46 100644 --- a/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/pom.xml +++ b/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/mixedreality/azure-mixedreality-authentication/pom.xml b/sdk/mixedreality/azure-mixedreality-authentication/pom.xml index 7d31410e6bed8..9315c02c9a29b 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/pom.xml +++ b/sdk/mixedreality/azure-mixedreality-authentication/pom.xml @@ -34,31 +34,31 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -94,7 +94,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -119,7 +119,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/mixedreality/azure-resourcemanager-mixedreality/pom.xml b/sdk/mixedreality/azure-resourcemanager-mixedreality/pom.xml index f5c8a81aaaf0c..fef5c414467d6 100644 --- a/sdk/mixedreality/azure-resourcemanager-mixedreality/pom.xml +++ b/sdk/mixedreality/azure-resourcemanager-mixedreality/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/pom.xml b/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/pom.xml index 0f68e92c836ab..5d4c26f41c774 100644 --- a/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/pom.xml +++ b/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/modelsrepository/azure-iot-modelsrepository/pom.xml b/sdk/modelsrepository/azure-iot-modelsrepository/pom.xml index 080ca46322809..84c0f6050e97c 100644 --- a/sdk/modelsrepository/azure-iot-modelsrepository/pom.xml +++ b/sdk/modelsrepository/azure-iot-modelsrepository/pom.xml @@ -46,37 +46,37 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -148,7 +148,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/monitor/azure-monitor-ingestion-perf/pom.xml b/sdk/monitor/azure-monitor-ingestion-perf/pom.xml index 994742bd97fc5..9d6fbf46217fd 100644 --- a/sdk/monitor/azure-monitor-ingestion-perf/pom.xml +++ b/sdk/monitor/azure-monitor-ingestion-perf/pom.xml @@ -36,18 +36,18 @@ com.azure azure-identity - 1.12.0 + 1.12.1 com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/monitor/azure-monitor-ingestion/README.md b/sdk/monitor/azure-monitor-ingestion/README.md index 9746b6520b989..8dd87e5055e3e 100644 --- a/sdk/monitor/azure-monitor-ingestion/README.md +++ b/sdk/monitor/azure-monitor-ingestion/README.md @@ -76,7 +76,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/monitor/azure-monitor-ingestion/pom.xml b/sdk/monitor/azure-monitor-ingestion/pom.xml index 751db19ef054d..31ac26fe70645 100644 --- a/sdk/monitor/azure-monitor-ingestion/pom.xml +++ b/sdk/monitor/azure-monitor-ingestion/pom.xml @@ -66,12 +66,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -101,7 +101,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -113,7 +113,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test 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 eda79ce1ec45c..fca9777060ae2 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 db75340d1d7ae..afc99a8bb5abf 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/pom.xml b/sdk/monitor/azure-monitor-opentelemetry-exporter/pom.xml index 48e3d98c420a5..cc0f04e15e927 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/pom.xml +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 io.opentelemetry @@ -164,13 +164,13 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 test com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -182,7 +182,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test 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 2a0c259da7fcf..8d3c424251c75 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/AppConfigurationExporterIntegrationTest.java b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/AppConfigurationExporterIntegrationTest.java index 1bc4b6a5762cd..4382cf8b9f861 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/AppConfigurationExporterIntegrationTest.java +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/AppConfigurationExporterIntegrationTest.java @@ -9,7 +9,7 @@ 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.annotation.LiveOnly; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.data.appconfiguration.ConfigurationClient; @@ -20,11 +20,8 @@ import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInfo; import reactor.core.publisher.Mono; import java.io.ByteArrayInputStream; @@ -38,15 +35,8 @@ import static com.azure.core.util.tracing.Tracer.DISABLE_TRACING_KEY; import static org.junit.jupiter.api.Assertions.assertTrue; +@LiveOnly public class AppConfigurationExporterIntegrationTest extends MonitorExporterClientTestBase { - - @Override - @BeforeEach - public void setupTest(TestInfo testInfo) { - Assumptions.assumeFalse(getTestMode() == TestMode.PLAYBACK, "Skipping playback tests"); - super.setupTest(testInfo); - } - @Test public void setConfigurationTest() throws InterruptedException { CountDownLatch exporterCountDown = new CountDownLatch(1); diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/EventHubsExporterIntegrationTest.java b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/EventHubsExporterIntegrationTest.java index 47ca3a62a5652..8469d11c63143 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/EventHubsExporterIntegrationTest.java +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/EventHubsExporterIntegrationTest.java @@ -4,7 +4,7 @@ package com.azure.monitor.opentelemetry.exporter; import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.test.TestMode; +import com.azure.core.test.annotation.LiveOnly; import com.azure.core.util.FluxUtil; import com.azure.messaging.eventhubs.EventData; import com.azure.messaging.eventhubs.EventHubClientBuilder; @@ -20,11 +20,8 @@ import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInfo; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; @@ -33,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; +@LiveOnly public class EventHubsExporterIntegrationTest extends MonitorExporterClientTestBase { private static final String CONNECTION_STRING = @@ -41,13 +39,6 @@ public class EventHubsExporterIntegrationTest extends MonitorExporterClientTestB System.getenv("STORAGE_CONNECTION_STRING"); private static final String CONTAINER_NAME = System.getenv("STORAGE_CONTAINER_NAME"); - @Override - @BeforeEach - public void setupTest(TestInfo testInfo) { - Assumptions.assumeFalse(getTestMode() == TestMode.PLAYBACK, "Skipping playback tests"); - super.setupTest(testInfo); - } - @Test public void producerTest() throws InterruptedException { CountDownLatch exporterCountDown = new CountDownLatch(2); 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 a08c30811c669..45d3676a11fd5 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/monitor/azure-monitor-query-perf/pom.xml b/sdk/monitor/azure-monitor-query-perf/pom.xml index 11f9abccaebb7..d398951cb5a2f 100644 --- a/sdk/monitor/azure-monitor-query-perf/pom.xml +++ b/sdk/monitor/azure-monitor-query-perf/pom.xml @@ -36,18 +36,18 @@ com.azure azure-identity - 1.12.0 + 1.12.1 com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/monitor/azure-monitor-query/README.md b/sdk/monitor/azure-monitor-query/README.md index 257508df5ac94..a3061aeed4303 100644 --- a/sdk/monitor/azure-monitor-query/README.md +++ b/sdk/monitor/azure-monitor-query/README.md @@ -86,7 +86,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/monitor/azure-monitor-query/pom.xml b/sdk/monitor/azure-monitor-query/pom.xml index 8571b6eeb3ee4..96dc29243de27 100644 --- a/sdk/monitor/azure-monitor-query/pom.xml +++ b/sdk/monitor/azure-monitor-query/pom.xml @@ -42,12 +42,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -75,19 +75,19 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 test diff --git a/sdk/mysql/azure-resourcemanager-mysql/pom.xml b/sdk/mysql/azure-resourcemanager-mysql/pom.xml index 113e566c44426..89d02b81952a8 100644 --- a/sdk/mysql/azure-resourcemanager-mysql/pom.xml +++ b/sdk/mysql/azure-resourcemanager-mysql/pom.xml @@ -45,23 +45,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/pom.xml b/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/pom.xml index f210688ae6e31..62a2d8568f3dd 100644 --- a/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/pom.xml +++ b/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/netapp/azure-resourcemanager-netapp/pom.xml b/sdk/netapp/azure-resourcemanager-netapp/pom.xml index 2793955041096..8b3f2f83c4ab4 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/pom.xml +++ b/sdk/netapp/azure-resourcemanager-netapp/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/networkanalytics/azure-resourcemanager-networkanalytics/pom.xml b/sdk/networkanalytics/azure-resourcemanager-networkanalytics/pom.xml index 56bb521f33ace..b96ce3ab166f8 100644 --- a/sdk/networkanalytics/azure-resourcemanager-networkanalytics/pom.xml +++ b/sdk/networkanalytics/azure-resourcemanager-networkanalytics/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/pom.xml b/sdk/networkcloud/azure-resourcemanager-networkcloud/pom.xml index c6fa5824190e6..9ddb398ad77df 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/pom.xml +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/networkfunction/azure-resourcemanager-networkfunction/pom.xml b/sdk/networkfunction/azure-resourcemanager-networkfunction/pom.xml index 8fcf731728f37..b86c7ad58bb21 100644 --- a/sdk/networkfunction/azure-resourcemanager-networkfunction/pom.xml +++ b/sdk/networkfunction/azure-resourcemanager-networkfunction/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/pom.xml b/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/pom.xml index b472147da2283..124e60f80f168 100644 --- a/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/pom.xml +++ b/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/nginx/azure-resourcemanager-nginx/pom.xml b/sdk/nginx/azure-resourcemanager-nginx/pom.xml index b7bf2678fb693..5213d1960d968 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/pom.xml +++ b/sdk/nginx/azure-resourcemanager-nginx/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/notificationhubs/azure-resourcemanager-notificationhubs/pom.xml b/sdk/notificationhubs/azure-resourcemanager-notificationhubs/pom.xml index cde4dd9b329f4..532b228bc9425 100644 --- a/sdk/notificationhubs/azure-resourcemanager-notificationhubs/pom.xml +++ b/sdk/notificationhubs/azure-resourcemanager-notificationhubs/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/oep/azure-resourcemanager-oep/pom.xml b/sdk/oep/azure-resourcemanager-oep/pom.xml index b4eb3143c263f..c06508942cfb3 100644 --- a/sdk/oep/azure-resourcemanager-oep/pom.xml +++ b/sdk/oep/azure-resourcemanager-oep/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/openai/azure-ai-openai-assistants/pom.xml b/sdk/openai/azure-ai-openai-assistants/pom.xml index a549f206d3cd6..f2c4f8e177a16 100644 --- a/sdk/openai/azure-ai-openai-assistants/pom.xml +++ b/sdk/openai/azure-ai-openai-assistants/pom.xml @@ -61,12 +61,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -81,25 +81,25 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -148,7 +148,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 993a2317dab3c..d13c415ca6079 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 372aef1d87110..e0b8132b6ee1f 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 c303e758c9883..0c41110a5607d 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 ce08fa777d936..5ea7a4570741f 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 50182c461a08a..231da68f73444 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 e9ad5a5fd64fc..3ab9b625ba3e5 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 035e80e9a8ff5..fc56f839db044 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 294165e1d1563..1cf4ddf547b39 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/CHANGELOG.md b/sdk/openai/azure-ai-openai/CHANGELOG.md index f55ace25c53e0..257f4ed1ae686 100644 --- a/sdk/openai/azure-ai-openai/CHANGELOG.md +++ b/sdk/openai/azure-ai-openai/CHANGELOG.md @@ -21,6 +21,7 @@ ### Breaking Changes +- Replaced Jackson Databind annotations with `azure-json` functionality for OpenAI service models. - [AOAI] Added a new class `ContentFilterDetailedResults` to represent detailed content filter results, which replaces the `customBlocklists` response property type, `List` in `ContentFilterResultDetailsForPrompt` and `ContentFilterResultsForChoice` class. diff --git a/sdk/openai/azure-ai-openai/README.md b/sdk/openai/azure-ai-openai/README.md index a5931f79b513e..b026469534550 100644 --- a/sdk/openai/azure-ai-openai/README.md +++ b/sdk/openai/azure-ai-openai/README.md @@ -105,7 +105,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/openai/azure-ai-openai/assets.json b/sdk/openai/azure-ai-openai/assets.json index e372abd69ef5f..5ade4481ff337 100644 --- a/sdk/openai/azure-ai-openai/assets.json +++ b/sdk/openai/azure-ai-openai/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/openai/azure-ai-openai", - "Tag": "java/openai/azure-ai-openai_8fd1810cfb" + "Tag": "java/openai/azure-ai-openai_589fab4377" } diff --git a/sdk/openai/azure-ai-openai/customization/src/main/java/ChatCompletionsToolCallCustomizations.java b/sdk/openai/azure-ai-openai/customization/src/main/java/OpenAICustomizations.java similarity index 51% rename from sdk/openai/azure-ai-openai/customization/src/main/java/ChatCompletionsToolCallCustomizations.java rename to sdk/openai/azure-ai-openai/customization/src/main/java/OpenAICustomizations.java index 57ab4bbc97ef3..d780093563a6b 100644 --- a/sdk/openai/azure-ai-openai/customization/src/main/java/ChatCompletionsToolCallCustomizations.java +++ b/sdk/openai/azure-ai-openai/customization/src/main/java/OpenAICustomizations.java @@ -14,51 +14,17 @@ /** * This class contains the customization code to customize the AutoRest generated code for OpenAI. */ -public class ChatCompletionsToolCallCustomizations extends Customization { +public class OpenAICustomizations extends Customization { @Override public void customize(LibraryCustomization customization, Logger logger) { - customizeChatCompletionsToolCall(customization, logger); - customizeEmbeddingEncodingFormatClass(customization, logger); - customizeEmbeddingsOptions(customization, logger); - } - - public void customizeChatCompletionsToolCall(LibraryCustomization customization, Logger logger) { - logger.info("Customizing the ChatCompletionsToolCall class"); - PackageCustomization packageCustomization = customization.getPackage("com.azure.ai.openai.models"); - ClassCustomization classCustomization = packageCustomization.getClass("ChatCompletionsToolCall"); - - // Replace JsonTypeInfo annotation - classCustomization.removeAnnotation("JsonTypeInfo"); - classCustomization.addAnnotation("JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, defaultImpl = ChatCompletionsToolCall.class)"); - - // Edit constructor - ConstructorCustomization constructorCustomization = classCustomization.getConstructor("ChatCompletionsToolCall") - .replaceParameters("@JsonProperty(value = \"id\") String id, @JsonProperty(value = \"type\")String type") - .replaceBody(joinWithNewline( - "this.id = id;", - "this.type = type;")); - JavadocCustomization constructorJavadocCustomization = constructorCustomization.getJavadoc() - .setParam("type", "the type value to set."); - - // Remove type and getter in ChatCompletionsFunctionToolCall - classCustomization = packageCustomization.getClass("ChatCompletionsFunctionToolCall"); - classCustomization.removeMethod("getType"); - classCustomization.customizeAst(compilationUnit -> { - ClassOrInterfaceDeclaration clazz = compilationUnit.getClassByName("ChatCompletionsFunctionToolCall").get(); - clazz.getMembers().removeIf(node -> { - if (node.isFieldDeclaration() - && node.asFieldDeclaration().getVariables() != null && !node.asFieldDeclaration().getVariables().isEmpty()) { - return "type".equals(node.asFieldDeclaration().getVariables().get(0).getName().asString()); - } - return false; - }); - }); - // remove unused class (no reference to them, after partial-update) customization.getRawEditor().removeFile("src/main/java/com/azure/ai/openai/models/FileDetails.java"); customization.getRawEditor().removeFile("src/main/java/com/azure/ai/openai/implementation/MultipartFormDataHelper.java"); + customizeEmbeddingEncodingFormatClass(customization, logger); + customizeEmbeddingsOptions(customization, logger); } + private void customizeEmbeddingEncodingFormatClass(LibraryCustomization customization, Logger logger) { logger.info("Customizing the EmbeddingEncodingFormat class"); ClassCustomization embeddingEncodingFormatClass = customization.getPackage("com.azure.ai.openai.models").getClass("EmbeddingEncodingFormat"); diff --git a/sdk/openai/azure-ai-openai/pom.xml b/sdk/openai/azure-ai-openai/pom.xml index 3a9916a6dab0b..d6e636c28fc75 100644 --- a/sdk/openai/azure-ai-openai/pom.xml +++ b/sdk/openai/azure-ai-openai/pom.xml @@ -49,8 +49,6 @@ --add-exports com.azure.core/com.azure.core.implementation.http=ALL-UNNAMED --add-exports com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED --add-opens com.azure.ai.openai/com.azure.ai.openai=ALL-UNNAMED - --add-opens com.azure.ai.openai/com.azure.ai.openai.implementation=com.fasterxml.jackson.databind - --add-opens com.azure.ai.openai/com.azure.ai.openai.functions=com.fasterxml.jackson.databind @@ -60,12 +58,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -80,13 +78,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -98,13 +96,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -145,7 +143,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIAsyncClient.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIAsyncClient.java index 5ae6a722a84e1..75d0e3814008e 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIAsyncClient.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIAsyncClient.java @@ -32,13 +32,6 @@ import com.azure.core.util.FluxUtil; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import static com.azure.ai.openai.implementation.AudioTranscriptionValidator.validateAudioResponseFormatForTranscription; -import static com.azure.ai.openai.implementation.AudioTranscriptionValidator.validateAudioResponseFormatForTranscriptionText; -import static com.azure.ai.openai.implementation.AudioTranslationValidator.validateAudioResponseFormatForTranslation; -import static com.azure.ai.openai.implementation.AudioTranslationValidator.validateAudioResponseFormatForTranslationText; -import static com.azure.ai.openai.implementation.EmbeddingsUtils.addEncodingFormat; -import static com.azure.ai.openai.implementation.NonAzureOpenAIClientImpl.addModelIdJson; -import static com.azure.core.util.FluxUtil.monoError; import com.azure.ai.openai.implementation.CompletionsUtils; import com.azure.ai.openai.implementation.MultipartDataHelper; import com.azure.ai.openai.implementation.MultipartDataSerializationResult; @@ -46,9 +39,15 @@ import com.azure.ai.openai.implementation.OpenAIServerSentEvents; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; -import com.fasterxml.jackson.core.JsonProcessingException; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicReference; +import static com.azure.ai.openai.implementation.AudioTranscriptionValidator.validateAudioResponseFormatForTranscription; +import static com.azure.ai.openai.implementation.AudioTranscriptionValidator.validateAudioResponseFormatForTranscriptionText; +import static com.azure.ai.openai.implementation.AudioTranslationValidator.validateAudioResponseFormatForTranslation; +import static com.azure.ai.openai.implementation.AudioTranslationValidator.validateAudioResponseFormatForTranslationText; +import static com.azure.ai.openai.implementation.EmbeddingsUtils.addEncodingFormat; +import static com.azure.ai.openai.implementation.NonAzureOpenAIClientImpl.addModelIdJson; +import static com.azure.core.util.FluxUtil.monoError; /** * Initializes a new instance of the asynchronous OpenAIClient type. @@ -140,15 +139,12 @@ public final class OpenAIAsyncClient { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getEmbeddingsWithResponse(String deploymentOrModelName, BinaryData embeddingsOptions, RequestOptions requestOptions) { - try { - embeddingsOptions = addEncodingFormat(embeddingsOptions); - } catch (JsonProcessingException e) { - return Mono.error(new RuntimeException(e)); - } + final BinaryData embeddingsOptionsUpdated = addEncodingFormat(embeddingsOptions); return openAIServiceClient != null - ? openAIServiceClient.getEmbeddingsWithResponseAsync(deploymentOrModelName, embeddingsOptions, + ? openAIServiceClient.getEmbeddingsWithResponseAsync(deploymentOrModelName, embeddingsOptionsUpdated, requestOptions) - : serviceClient.getEmbeddingsWithResponseAsync(deploymentOrModelName, embeddingsOptions, requestOptions); + : serviceClient.getEmbeddingsWithResponseAsync(deploymentOrModelName, embeddingsOptionsUpdated, + requestOptions); } /** @@ -1482,17 +1478,13 @@ Mono getAudioTranslationAsResponseObject(String deploymentOrMo public Mono> generateSpeechFromTextWithResponse(String deploymentOrModelName, BinaryData speechGenerationOptions, RequestOptions requestOptions) { // modelId is part of the request body in nonAzure OpenAI - try { - BinaryData speechGenerationOptionsWithModelId - = addModelIdJson(speechGenerationOptions, deploymentOrModelName); - return this.openAIServiceClient != null - ? this.openAIServiceClient.generateSpeechFromTextWithResponseAsync(deploymentOrModelName, - speechGenerationOptionsWithModelId, requestOptions) - : this.serviceClient.generateSpeechFromTextWithResponseAsync(deploymentOrModelName, - speechGenerationOptionsWithModelId, requestOptions); - } catch (JsonProcessingException e) { - return Mono.error(e); - } + final BinaryData speechGenerationOptionsWithModelId + = addModelIdJson(speechGenerationOptions, deploymentOrModelName); + return this.openAIServiceClient != null + ? this.openAIServiceClient.generateSpeechFromTextWithResponseAsync(deploymentOrModelName, + speechGenerationOptionsWithModelId, requestOptions) + : this.serviceClient.generateSpeechFromTextWithResponseAsync(deploymentOrModelName, + speechGenerationOptionsWithModelId, requestOptions); } /** diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIClient.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIClient.java index 871f12f0b20ed..1ac8575aeafbe 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIClient.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIClient.java @@ -30,12 +30,6 @@ import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.BinaryData; import com.azure.core.util.logging.ClientLogger; -import static com.azure.ai.openai.implementation.AudioTranscriptionValidator.validateAudioResponseFormatForTranscription; -import static com.azure.ai.openai.implementation.AudioTranscriptionValidator.validateAudioResponseFormatForTranscriptionText; -import static com.azure.ai.openai.implementation.AudioTranslationValidator.validateAudioResponseFormatForTranslation; -import static com.azure.ai.openai.implementation.AudioTranslationValidator.validateAudioResponseFormatForTranslationText; -import static com.azure.ai.openai.implementation.EmbeddingsUtils.addEncodingFormat; -import static com.azure.ai.openai.implementation.NonAzureOpenAIClientImpl.addModelIdJson; import com.azure.ai.openai.implementation.CompletionsUtils; import com.azure.ai.openai.implementation.MultipartDataHelper; import com.azure.ai.openai.implementation.MultipartDataSerializationResult; @@ -43,9 +37,14 @@ import com.azure.ai.openai.implementation.OpenAIServerSentEvents; import com.azure.core.util.CoreUtils; import com.azure.core.util.IterableStream; -import com.fasterxml.jackson.core.JsonProcessingException; -import java.nio.ByteBuffer; import reactor.core.publisher.Flux; +import java.nio.ByteBuffer; +import static com.azure.ai.openai.implementation.AudioTranscriptionValidator.validateAudioResponseFormatForTranscription; +import static com.azure.ai.openai.implementation.AudioTranscriptionValidator.validateAudioResponseFormatForTranscriptionText; +import static com.azure.ai.openai.implementation.AudioTranslationValidator.validateAudioResponseFormatForTranslation; +import static com.azure.ai.openai.implementation.AudioTranslationValidator.validateAudioResponseFormatForTranslationText; +import static com.azure.ai.openai.implementation.EmbeddingsUtils.addEncodingFormat; +import static com.azure.ai.openai.implementation.NonAzureOpenAIClientImpl.addModelIdJson; /** * Initializes a new instance of the synchronous OpenAIClient type. @@ -133,14 +132,11 @@ public final class OpenAIClient { @ServiceMethod(returns = ReturnType.SINGLE) public Response getEmbeddingsWithResponse(String deploymentOrModelName, BinaryData embeddingsOptions, RequestOptions requestOptions) { - try { - embeddingsOptions = addEncodingFormat(embeddingsOptions); - } catch (JsonProcessingException e) { - throw LOGGER.logExceptionAsWarning(new RuntimeException(e)); - } + final BinaryData embeddingsOptionsUpdated = addEncodingFormat(embeddingsOptions); return openAIServiceClient != null - ? openAIServiceClient.getEmbeddingsWithResponse(deploymentOrModelName, embeddingsOptions, requestOptions) - : serviceClient.getEmbeddingsWithResponse(deploymentOrModelName, embeddingsOptions, requestOptions); + ? openAIServiceClient.getEmbeddingsWithResponse(deploymentOrModelName, embeddingsOptionsUpdated, + requestOptions) + : serviceClient.getEmbeddingsWithResponse(deploymentOrModelName, embeddingsOptionsUpdated, requestOptions); } /** @@ -1441,12 +1437,8 @@ AudioTranslation getAudioTranslationAsResponseObject(String deploymentOrModelNam @ServiceMethod(returns = ReturnType.SINGLE) public Response generateSpeechFromTextWithResponse(String deploymentOrModelName, BinaryData speechGenerationOptions, RequestOptions requestOptions) { - BinaryData speechGenerationOptionsWithModelId = null; - try { - speechGenerationOptionsWithModelId = addModelIdJson(speechGenerationOptions, deploymentOrModelName); - } catch (JsonProcessingException e) { - throw LOGGER.logExceptionAsError(new RuntimeException(e)); - } + final BinaryData speechGenerationOptionsWithModelId + = addModelIdJson(speechGenerationOptions, deploymentOrModelName); return openAIServiceClient != null ? this.openAIServiceClient.generateSpeechFromTextWithResponse(speechGenerationOptionsWithModelId, requestOptions) diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/EmbeddingsUtils.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/EmbeddingsUtils.java index 85e0f60312097..c0d88f487d544 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/EmbeddingsUtils.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/EmbeddingsUtils.java @@ -5,37 +5,28 @@ import com.azure.core.util.Base64Util; import com.azure.core.util.BinaryData; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; +import java.util.Map; /** This class contains convenience methods and constants for operations related to Embeddings */ public final class EmbeddingsUtils { - private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); // This method applies to both AOAI and OAI clients - public static BinaryData addEncodingFormat(BinaryData inputJson) throws JsonProcessingException { + @SuppressWarnings("unchecked") + public static BinaryData addEncodingFormat(BinaryData inputJson) { + Map mapJson = inputJson.toObject(Map.class); - JsonNode jsonNode = JSON_MAPPER.readTree(inputJson.toString()); - if (jsonNode instanceof ObjectNode) { - ObjectNode objectNode = (ObjectNode) jsonNode; - if (objectNode.has("encoding_format")) { - return inputJson; - } - - objectNode.put("encoding_format", "base64"); - inputJson = BinaryData.fromBytes(objectNode.toString().getBytes(StandardCharsets.UTF_8)); + if (mapJson.containsKey("encoding_format")) { + return inputJson; } - return inputJson; + mapJson.put("encoding_format", "base64"); + return BinaryData.fromObject(mapJson); } // This method converts a base64 string to a list of floats diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/NonAzureOpenAIClientImpl.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/NonAzureOpenAIClientImpl.java index 71a55709bf9d3..1933ccea26abf 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/NonAzureOpenAIClientImpl.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/NonAzureOpenAIClientImpl.java @@ -25,13 +25,9 @@ import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.serializer.SerializerAdapter; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; import reactor.core.publisher.Mono; -import java.nio.charset.StandardCharsets; +import java.util.Map; /** * Implementation for calling Non-Azure OpenAI Service @@ -69,11 +65,6 @@ public SerializerAdapter getSerializerAdapter() { */ public static final String OPEN_AI_ENDPOINT = "https://api.openai.com/v1"; - /** - * Mapper used to add the `modelId` into the request body for an nonAzure OpenAI request - */ - private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - /** * Initializes an instance of OpenAIClient client. * @@ -474,14 +465,8 @@ Response generateSpeechFromTextSync( public Mono> getEmbeddingsWithResponseAsync(String modelId, BinaryData embeddingsOptions, RequestOptions requestOptions) { final String accept = "application/json"; - // modelId is part of the request body in nonAzure OpenAI - try { - embeddingsOptions = addModelIdJson(embeddingsOptions, modelId); - } catch (JsonProcessingException e) { - return Mono.error(e); - } - final BinaryData embeddingsOptionsUpdated = embeddingsOptions; + final BinaryData embeddingsOptionsUpdated = addModelIdJson(embeddingsOptions, modelId); return FluxUtil.withContext( context -> service.getEmbeddings( @@ -543,14 +528,8 @@ public Mono> getEmbeddingsWithResponseAsync(String modelId, public Response getEmbeddingsWithResponse(String modelId, BinaryData embeddingsOptions, RequestOptions requestOptions) { final String accept = "application/json"; - // modelId is part of the request body in nonAzure OpenAI - try { - embeddingsOptions = addModelIdJson(embeddingsOptions, modelId); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - BinaryData embeddingsOptionsUpdated = embeddingsOptions; + final BinaryData embeddingsOptionsUpdated = addModelIdJson(embeddingsOptions, modelId); return service.getEmbeddingsSync( OPEN_AI_ENDPOINT, accept, @@ -645,21 +624,16 @@ public Response getEmbeddingsWithResponse(String modelId, BinaryData public Mono> getCompletionsWithResponseAsync(String modelId, BinaryData completionsOptions, RequestOptions requestOptions) { final String accept = "application/json"; - // modelId is part of the request body in nonAzure OpenAI - try { - BinaryData completionsOptionsUpdated = addModelIdJson(completionsOptions, modelId); - return FluxUtil.withContext( - context -> - service.getCompletions( - OPEN_AI_ENDPOINT, - accept, - completionsOptionsUpdated, - requestOptions, - context)); - } catch (JsonProcessingException e) { - return Mono.error(e); - } + final BinaryData completionsOptionsUpdated = addModelIdJson(completionsOptions, modelId); + return FluxUtil.withContext( + context -> + service.getCompletions( + OPEN_AI_ENDPOINT, + accept, + completionsOptionsUpdated, + requestOptions, + context)); } /** @@ -746,15 +720,8 @@ public Mono> getCompletionsWithResponseAsync(String modelId public Response getCompletionsWithResponse(String modelId, BinaryData completionsOptions, RequestOptions requestOptions) { final String accept = "application/json"; - // modelId is part of the request body in nonAzure OpenAI - BinaryData completionsOptionsUpdated = null; - try { - completionsOptionsUpdated = addModelIdJson(completionsOptions, modelId); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - + final BinaryData completionsOptionsUpdated = addModelIdJson(completionsOptions, modelId); return service.getCompletionsSync( OPEN_AI_ENDPOINT, accept, @@ -840,21 +807,16 @@ public Response getCompletionsWithResponse(String modelId, BinaryDat public Mono> getChatCompletionsWithResponseAsync(String modelId, BinaryData chatCompletionsOptions, RequestOptions requestOptions) { final String accept = "application/json"; - // modelId is part of the request body in nonAzure OpenAI - try { - BinaryData chatCompletionsOptionsUpdated = addModelIdJson(chatCompletionsOptions, modelId); - return FluxUtil.withContext( - context -> - service.getChatCompletions( - OPEN_AI_ENDPOINT, - accept, - chatCompletionsOptionsUpdated, - requestOptions, - context)); - } catch (JsonProcessingException e) { - return Mono.error(e); - } + final BinaryData chatCompletionsOptionsUpdated = addModelIdJson(chatCompletionsOptions, modelId); + return FluxUtil.withContext( + context -> + service.getChatCompletions( + OPEN_AI_ENDPOINT, + accept, + chatCompletionsOptionsUpdated, + requestOptions, + context)); } /** @@ -933,15 +895,8 @@ public Mono> getChatCompletionsWithResponseAsync(String mod public Response getChatCompletionsWithResponse(String modelId, BinaryData chatCompletionsOptions, RequestOptions requestOptions) { final String accept = "application/json"; - // modelId is part of the request body in nonAzure OpenAI - BinaryData chatCompletionsOptionsUpdated = null; - try { - chatCompletionsOptionsUpdated = addModelIdJson(chatCompletionsOptions, modelId); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - + final BinaryData chatCompletionsOptionsUpdated = addModelIdJson(chatCompletionsOptions, modelId); return service.getChatCompletionsSync( OPEN_AI_ENDPOINT, accept, @@ -997,21 +952,16 @@ public Response getChatCompletionsWithResponse(String modelId, Binar public Mono> getImageGenerationsWithResponseAsync(String modelId, BinaryData imageGenerationOptions, RequestOptions requestOptions) { final String accept = "application/json"; - // modelId is part of the request body in nonAzure OpenAI - try { - BinaryData imageGenerationOptionsUpdated = addModelIdJson(imageGenerationOptions, modelId); - return FluxUtil.withContext( - context -> - service.getImageGenerations( - OPEN_AI_ENDPOINT, - accept, - imageGenerationOptionsUpdated, - requestOptions, - context)); - } catch (JsonProcessingException e) { - return Mono.error(e); - } + final BinaryData imageGenerationOptionsUpdated = addModelIdJson(imageGenerationOptions, modelId); + return FluxUtil.withContext( + context -> + service.getImageGenerations( + OPEN_AI_ENDPOINT, + accept, + imageGenerationOptionsUpdated, + requestOptions, + context)); } /** @@ -1061,13 +1011,7 @@ public Mono> getImageGenerationsWithResponseAsync(String mo public Response getImageGenerationsWithResponse(String modelId, BinaryData imageGenerationOptions, RequestOptions requestOptions) { final String accept = "application/json"; - BinaryData imageGenerationOptionsUpdated = null; - try { - imageGenerationOptionsUpdated = addModelIdJson(imageGenerationOptions, modelId); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - + final BinaryData imageGenerationOptionsUpdated = addModelIdJson(imageGenerationOptions, modelId); return service.getImageGenerationsSync( OPEN_AI_ENDPOINT, accept, @@ -1086,16 +1030,11 @@ public Response getImageGenerationsWithResponse(String modelId, * @param modelId The LLM model ID to be injected in the JSON * @return an updated version of the JSON with the key "model" and its corresponding value "modelId" added */ - public static BinaryData addModelIdJson(BinaryData inputJson, String modelId) throws JsonProcessingException { - JsonNode jsonNode = JSON_MAPPER.readTree(inputJson.toString()); - if (jsonNode instanceof ObjectNode) { - ObjectNode objectNode = (ObjectNode) jsonNode; - objectNode.put("model", modelId); - inputJson = BinaryData.fromBytes( - objectNode.toString() - .getBytes(StandardCharsets.UTF_8)); - } - + @SuppressWarnings("unchecked") + public static BinaryData addModelIdJson(BinaryData inputJson, String modelId) { + Map mapJson = inputJson.toObject(Map.class); + mapJson.put("model", modelId); + inputJson = BinaryData.fromObject(mapJson); return inputJson; } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/OpenAIServerSentEvents.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/OpenAIServerSentEvents.java index dbdfc3d5f8aaf..d8706d0333351 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/OpenAIServerSentEvents.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/OpenAIServerSentEvents.java @@ -3,14 +3,13 @@ package com.azure.ai.openai.implementation; -import com.azure.core.util.logging.ClientLogger; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; +import com.azure.core.util.serializer.JsonSerializer; +import com.azure.core.util.serializer.JsonSerializerProviders; +import com.azure.core.util.serializer.TypeReference; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; - import java.io.ByteArrayOutputStream; +import java.io.UncheckedIOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -21,18 +20,11 @@ public final class OpenAIServerSentEvents { private static final List STREAM_COMPLETION_EVENT = Arrays.asList("data: [DONE]", "data:[DONE]"); - - private static final ClientLogger LOGGER = new ClientLogger(OpenAIServerSentEvents.class); private final Flux source; private final Class type; private ByteArrayOutputStream outStream; - private static final ObjectMapper SERIALIZER = new ObjectMapper() - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) - .disable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES) - .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); + private static final JsonSerializer SERIALIZER = JsonSerializerProviders.createInstance(true); public OpenAIServerSentEvents(Flux source, Class type) { this.source = source; @@ -52,11 +44,9 @@ private Flux mapByteBuffersToEvents() { byte[] byteArray = byteBuffer.array(); for (byte currentByte : byteArray) { if (currentByte == 0xA || currentByte == 0xD) { - String currentLine; try { - currentLine = outStream.toString(StandardCharsets.UTF_8.name()); - handleCurrentLine(currentLine, values); - } catch (UnsupportedEncodingException | JsonProcessingException e) { + handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); + } catch (UnsupportedEncodingException | UncheckedIOException e) { return Flux.error(e); } outStream = new ByteArrayOutputStream(); @@ -67,7 +57,7 @@ private Flux mapByteBuffersToEvents() { try { handleCurrentLine(outStream.toString(StandardCharsets.UTF_8.name()), values); outStream = new ByteArrayOutputStream(); - } catch (IllegalStateException | JsonProcessingException e) { + } catch (IllegalStateException | UncheckedIOException e) { // return the values collected so far, as this could be because the server sent event is // split across two byte buffers and the last line is incomplete and will be continued in // the next byte buffer @@ -79,7 +69,7 @@ private Flux mapByteBuffersToEvents() { }).cache(); } - private void handleCurrentLine(String currentLine, List values) throws JsonProcessingException { + private void handleCurrentLine(String currentLine, List values) throws UncheckedIOException { if (currentLine.isEmpty() || STREAM_COMPLETION_EVENT.contains(currentLine)) { return; } @@ -95,7 +85,12 @@ private void handleCurrentLine(String currentLine, List values) throws JsonPr dataValue = split[1].substring(1); } - T value = SERIALIZER.readValue(dataValue, type); + T value = SERIALIZER.deserializeFromBytes(dataValue.getBytes(StandardCharsets.UTF_8), TypeReference.createInstance(type)); + if (value == null) { + throw new IllegalStateException("Failed to deserialize the data value " + dataValue); + } + values.add(value); + } } 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 ca6d625e6e308..0cb1ab118f36c 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 @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -45,7 +44,6 @@ public FunctionCallPreset() { * @return the corresponding FunctionCallPreset. */ @Generated - @JsonCreator public static FunctionCallPreset fromString(String name) { return fromString(name, FunctionCallPreset.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/models/package-info.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/models/package-info.java index 3585ee66b7802..f00df3b990feb 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/models/package-info.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/models/package-info.java @@ -2,6 +2,9 @@ // Licensed under the MIT License. // Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the data models for OpenAI. Azure OpenAI APIs for completions and search. + * + * Package containing the data models for OpenAI. + * Azure OpenAI APIs for completions and search. + * */ package com.azure.ai.openai.implementation.models; diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTaskLabel.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTaskLabel.java index e1c574edd29ea..335c6fcd707d5 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTaskLabel.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTaskLabel.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -42,7 +41,6 @@ public AudioTaskLabel() { * @return the corresponding AudioTaskLabel. */ @Generated - @JsonCreator public static AudioTaskLabel fromString(String name) { return fromString(name, AudioTaskLabel.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscription.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscription.java index eb2decf8c66c2..071a15517f769 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscription.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscription.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.time.Duration; import java.util.List; @@ -14,20 +17,18 @@ * Result information for an operation that transcribed spoken audio into written text. */ @Immutable -public final class AudioTranscription { +public final class AudioTranscription implements JsonSerializable { /* * The transcribed text for the provided audio data. */ @Generated - @JsonProperty(value = "text") private final String text; /* * The label that describes which operation type generated the accompanying response data. */ @Generated - @JsonProperty(value = "task") private AudioTaskLabel task; /* @@ -35,21 +36,18 @@ public final class AudioTranscription { * This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. */ @Generated - @JsonProperty(value = "language") private String language; /* * The total duration of the audio processed to produce accompanying transcription information. */ @Generated - @JsonProperty(value = "duration") private Double duration; /* * A collection of information about the timing, probabilities, and other detail of each processed audio segment. */ @Generated - @JsonProperty(value = "segments") private List segments; /** @@ -58,8 +56,7 @@ public final class AudioTranscription { * @param text the text value to set. */ @Generated - @JsonCreator - private AudioTranscription(@JsonProperty(value = "text") String text) { + private AudioTranscription(String text) { this.text = text; } @@ -123,7 +120,6 @@ public List getSegments() { * A collection of information about the timing of each processed word. */ @Generated - @JsonProperty(value = "words") private List words; /** @@ -135,4 +131,67 @@ public List getSegments() { public List getWords() { return this.words; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeStringField("task", this.task == null ? null : this.task.toString()); + jsonWriter.writeStringField("language", this.language); + jsonWriter.writeNumberField("duration", this.duration); + jsonWriter.writeArrayField("segments", this.segments, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("words", this.words, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AudioTranscription from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AudioTranscription 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 AudioTranscription. + */ + @Generated + public static AudioTranscription fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String text = null; + AudioTaskLabel task = null; + String language = null; + Double duration = null; + List segments = null; + List words = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("text".equals(fieldName)) { + text = reader.getString(); + } else if ("task".equals(fieldName)) { + task = AudioTaskLabel.fromString(reader.getString()); + } else if ("language".equals(fieldName)) { + language = reader.getString(); + } else if ("duration".equals(fieldName)) { + duration = reader.getNullable(JsonReader::getDouble); + } else if ("segments".equals(fieldName)) { + segments = reader.readArray(reader1 -> AudioTranscriptionSegment.fromJson(reader1)); + } else if ("words".equals(fieldName)) { + words = reader.readArray(reader1 -> AudioTranscriptionWord.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + AudioTranscription deserializedAudioTranscription = new AudioTranscription(text); + deserializedAudioTranscription.task = task; + deserializedAudioTranscription.language = language; + deserializedAudioTranscription.duration = duration; + deserializedAudioTranscription.segments = segments; + deserializedAudioTranscription.words = words; + return deserializedAudioTranscription; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionFormat.java index 163e5deb4058b..4a9ea7822f796 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionFormat.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionFormat.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -62,7 +61,6 @@ public AudioTranscriptionFormat() { * @return the corresponding AudioTranscriptionFormat. */ @Generated - @JsonCreator public static AudioTranscriptionFormat fromString(String name) { return fromString(name, AudioTranscriptionFormat.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionOptions.java index b292896c01f91..83b097696dc07 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionOptions.java @@ -5,8 +5,8 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import java.util.List; import com.azure.core.util.CoreUtils; +import java.util.List; /** * The configuration information for an audio transcription request. diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionSegment.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionSegment.java index a337a53de822c..c6b842c9b0c61 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionSegment.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionSegment.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.time.Duration; import java.util.List; @@ -16,69 +19,60 @@ * necessarily sentences. */ @Immutable -public final class AudioTranscriptionSegment { +public final class AudioTranscriptionSegment implements JsonSerializable { /* * The 0-based index of this segment within a transcription. */ @Generated - @JsonProperty(value = "id") private final int id; /* * The time at which this segment started relative to the beginning of the transcribed audio. */ @Generated - @JsonProperty(value = "start") private final double start; /* * The time at which this segment ended relative to the beginning of the transcribed audio. */ @Generated - @JsonProperty(value = "end") private final double end; /* * The transcribed text that was part of this audio segment. */ @Generated - @JsonProperty(value = "text") private final String text; /* * The temperature score associated with this audio segment. */ @Generated - @JsonProperty(value = "temperature") private final double temperature; /* * The average log probability associated with this audio segment. */ @Generated - @JsonProperty(value = "avg_logprob") private final double avgLogprob; /* * The compression ratio of this audio segment. */ @Generated - @JsonProperty(value = "compression_ratio") private final double compressionRatio; /* * The probability of no speech detection within this audio segment. */ @Generated - @JsonProperty(value = "no_speech_prob") private final double noSpeechProb; /* * The token IDs matching the transcribed text in this audio segment. */ @Generated - @JsonProperty(value = "tokens") private final List tokens; /* @@ -89,7 +83,6 @@ public final class AudioTranscriptionSegment { * segment's associated seek position. */ @Generated - @JsonProperty(value = "seek") private final int seek; /** @@ -129,18 +122,6 @@ private AudioTranscriptionSegment(int id, Duration start, Duration end, String t this.seek = seek; } - @Generated - @JsonCreator - private AudioTranscriptionSegment(@JsonProperty(value = "id") int id, @JsonProperty(value = "start") double start, - @JsonProperty(value = "end") double end, @JsonProperty(value = "text") String text, - @JsonProperty(value = "temperature") double temperature, @JsonProperty(value = "avg_logprob") double avgLogprob, - @JsonProperty(value = "compression_ratio") double compressionRatio, - @JsonProperty(value = "no_speech_prob") double noSpeechProb, - @JsonProperty(value = "tokens") List tokens, @JsonProperty(value = "seek") int seek) { - this(id, Duration.ofNanos((long) (start * 1000_000_000L)), Duration.ofNanos((long) (end * 1000_000_000L)), text, - temperature, avgLogprob, compressionRatio, noSpeechProb, tokens, seek); - } - /** * Get the id property: The 0-based index of this segment within a transcription. * @@ -246,4 +227,78 @@ public List getTokens() { public int getSeek() { return this.seek; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("id", this.id); + jsonWriter.writeDoubleField("start", this.start); + jsonWriter.writeDoubleField("end", this.end); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeDoubleField("temperature", this.temperature); + jsonWriter.writeDoubleField("avg_logprob", this.avgLogprob); + jsonWriter.writeDoubleField("compression_ratio", this.compressionRatio); + jsonWriter.writeDoubleField("no_speech_prob", this.noSpeechProb); + jsonWriter.writeArrayField("tokens", this.tokens, (writer, element) -> writer.writeInt(element)); + jsonWriter.writeIntField("seek", this.seek); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AudioTranscriptionSegment from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AudioTranscriptionSegment 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 AudioTranscriptionSegment. + */ + @Generated + public static AudioTranscriptionSegment fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + int id = 0; + Duration start = null; + Duration end = null; + String text = null; + double temperature = 0.0; + double avgLogprob = 0.0; + double compressionRatio = 0.0; + double noSpeechProb = 0.0; + List tokens = null; + int seek = 0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getInt(); + } else if ("start".equals(fieldName)) { + start = Duration.ofNanos((long) (reader.getDouble() * 1000_000_000L)); + } else if ("end".equals(fieldName)) { + end = Duration.ofNanos((long) (reader.getDouble() * 1000_000_000L)); + } else if ("text".equals(fieldName)) { + text = reader.getString(); + } else if ("temperature".equals(fieldName)) { + temperature = reader.getDouble(); + } else if ("avg_logprob".equals(fieldName)) { + avgLogprob = reader.getDouble(); + } else if ("compression_ratio".equals(fieldName)) { + compressionRatio = reader.getDouble(); + } else if ("no_speech_prob".equals(fieldName)) { + noSpeechProb = reader.getDouble(); + } else if ("tokens".equals(fieldName)) { + tokens = reader.readArray(reader1 -> reader1.getInt()); + } else if ("seek".equals(fieldName)) { + seek = reader.getInt(); + } else { + reader.skipChildren(); + } + } + return new AudioTranscriptionSegment(id, start, end, text, temperature, avgLogprob, compressionRatio, + noSpeechProb, tokens, seek); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionTimestampGranularity.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionTimestampGranularity.java index e533f68e4c285..99fd5d7a46e3b 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionTimestampGranularity.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionTimestampGranularity.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -45,7 +44,6 @@ public AudioTranscriptionTimestampGranularity() { * @return the corresponding AudioTranscriptionTimestampGranularity. */ @Generated - @JsonCreator public static AudioTranscriptionTimestampGranularity fromString(String name) { return fromString(name, AudioTranscriptionTimestampGranularity.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionWord.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionWord.java index 6c5910a3632a5..2faa2dee43816 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionWord.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranscriptionWord.java @@ -5,53 +5,38 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.Duration; /** * Extended information about a single transcribed word, as provided on responses when the 'word' timestamp granularity * is provided. */ @Immutable -public final class AudioTranscriptionWord { +public final class AudioTranscriptionWord implements JsonSerializable { /* * The textual content of the word. */ @Generated - @JsonProperty(value = "word") private final String word; /* * The start time of the word relative to the beginning of the audio, expressed in seconds. */ @Generated - @JsonProperty(value = "start") private final double start; /* * The end time of the word relative to the beginning of the audio, expressed in seconds. */ @Generated - @JsonProperty(value = "end") private final double end; - /** - * Creates an instance of AudioTranscriptionWord class. - * - * @param word the word value to set. - * @param start the start value to set. - * @param end the end value to set. - */ - @Generated - @JsonCreator - private AudioTranscriptionWord(@JsonProperty(value = "word") String word, - @JsonProperty(value = "start") double start, @JsonProperty(value = "end") double end) { - this.word = word; - this.start = start; - this.end = end; - } - /** * Get the word property: The textual content of the word. * @@ -68,8 +53,8 @@ public String getWord() { * @return the start value. */ @Generated - public double getStart() { - return this.start; + public Duration getStart() { + return Duration.ofNanos((long) (this.start * 1000_000_000L)); } /** @@ -78,7 +63,74 @@ public double getStart() { * @return the end value. */ @Generated - public double getEnd() { - return this.end; + public Duration getEnd() { + return Duration.ofNanos((long) (this.end * 1000_000_000L)); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("word", this.word); + jsonWriter.writeDoubleField("start", this.start); + jsonWriter.writeDoubleField("end", this.end); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AudioTranscriptionWord from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AudioTranscriptionWord 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 AudioTranscriptionWord. + */ + @Generated + public static AudioTranscriptionWord fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String word = null; + Duration start = null; + Duration end = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("word".equals(fieldName)) { + word = reader.getString(); + } else if ("start".equals(fieldName)) { + start = Duration.ofNanos((long) (reader.getDouble() * 1000_000_000L)); + } else if ("end".equals(fieldName)) { + end = Duration.ofNanos((long) (reader.getDouble() * 1000_000_000L)); + } else { + reader.skipChildren(); + } + } + return new AudioTranscriptionWord(word, start, end); + }); + } + + /** + * Creates an instance of AudioTranscriptionWord class. + * + * @param word the word value to set. + * @param start the start value to set. + * @param end the end value to set. + */ + @Generated + private AudioTranscriptionWord(String word, Duration start, Duration end) { + this.word = word; + if (start == null) { + this.start = 0.0; + } else { + this.start = (double) start.toNanos() / 1000_000_000L; + } + if (end == null) { + this.end = 0.0; + } else { + this.end = (double) end.toNanos() / 1000_000_000L; + } } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslation.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslation.java index 83f5f1366c110..f3e759cce3dbb 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslation.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslation.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.time.Duration; import java.util.List; @@ -14,20 +17,18 @@ * Result information for an operation that translated spoken audio into written text. */ @Immutable -public final class AudioTranslation { +public final class AudioTranslation implements JsonSerializable { /* * The translated text for the provided audio data. */ @Generated - @JsonProperty(value = "text") private final String text; /* * The label that describes which operation type generated the accompanying response data. */ @Generated - @JsonProperty(value = "task") private AudioTaskLabel task; /* @@ -35,21 +36,18 @@ public final class AudioTranslation { * This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. */ @Generated - @JsonProperty(value = "language") private String language; /* * The total duration of the audio processed to produce accompanying translation information. */ @Generated - @JsonProperty(value = "duration") private Double duration; /* * A collection of information about the timing, probabilities, and other detail of each processed audio segment. */ @Generated - @JsonProperty(value = "segments") private List segments; /** @@ -58,8 +56,7 @@ public final class AudioTranslation { * @param text the text value to set. */ @Generated - @JsonCreator - private AudioTranslation(@JsonProperty(value = "text") String text) { + private AudioTranslation(String text) { this.text = text; } @@ -118,4 +115,62 @@ public Duration getDuration() { public List getSegments() { return this.segments; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeStringField("task", this.task == null ? null : this.task.toString()); + jsonWriter.writeStringField("language", this.language); + jsonWriter.writeNumberField("duration", this.duration); + jsonWriter.writeArrayField("segments", this.segments, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AudioTranslation from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AudioTranslation 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 AudioTranslation. + */ + @Generated + public static AudioTranslation fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String text = null; + AudioTaskLabel task = null; + String language = null; + Double duration = null; + List segments = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("text".equals(fieldName)) { + text = reader.getString(); + } else if ("task".equals(fieldName)) { + task = AudioTaskLabel.fromString(reader.getString()); + } else if ("language".equals(fieldName)) { + language = reader.getString(); + } else if ("duration".equals(fieldName)) { + duration = reader.getNullable(JsonReader::getDouble); + } else if ("segments".equals(fieldName)) { + segments = reader.readArray(reader1 -> AudioTranslationSegment.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + AudioTranslation deserializedAudioTranslation = new AudioTranslation(text); + deserializedAudioTranslation.task = task; + deserializedAudioTranslation.language = language; + deserializedAudioTranslation.duration = duration; + deserializedAudioTranslation.segments = segments; + return deserializedAudioTranslation; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslationFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslationFormat.java index 64e6ddf8571f1..5b72a3f147e62 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslationFormat.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslationFormat.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -62,7 +61,6 @@ public AudioTranslationFormat() { * @return the corresponding AudioTranslationFormat. */ @Generated - @JsonCreator public static AudioTranslationFormat fromString(String name) { return fromString(name, AudioTranslationFormat.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslationSegment.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslationSegment.java index afa08c550ada2..26b00e46b09ed 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslationSegment.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioTranslationSegment.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.time.Duration; import java.util.List; @@ -16,69 +19,60 @@ * necessarily sentences. */ @Immutable -public final class AudioTranslationSegment { +public final class AudioTranslationSegment implements JsonSerializable { /* * The 0-based index of this segment within a translation. */ @Generated - @JsonProperty(value = "id") private final int id; /* * The time at which this segment started relative to the beginning of the translated audio. */ @Generated - @JsonProperty(value = "start") private final double start; /* * The time at which this segment ended relative to the beginning of the translated audio. */ @Generated - @JsonProperty(value = "end") private final double end; /* * The translated text that was part of this audio segment. */ @Generated - @JsonProperty(value = "text") private final String text; /* * The temperature score associated with this audio segment. */ @Generated - @JsonProperty(value = "temperature") private final double temperature; /* * The average log probability associated with this audio segment. */ @Generated - @JsonProperty(value = "avg_logprob") private final double avgLogprob; /* * The compression ratio of this audio segment. */ @Generated - @JsonProperty(value = "compression_ratio") private final double compressionRatio; /* * The probability of no speech detection within this audio segment. */ @Generated - @JsonProperty(value = "no_speech_prob") private final double noSpeechProb; /* * The token IDs matching the translated text in this audio segment. */ @Generated - @JsonProperty(value = "tokens") private final List tokens; /* @@ -89,7 +83,6 @@ public final class AudioTranslationSegment { * segment's associated seek position. */ @Generated - @JsonProperty(value = "seek") private final int seek; /** @@ -129,18 +122,6 @@ private AudioTranslationSegment(int id, Duration start, Duration end, String tex this.seek = seek; } - @Generated - @JsonCreator - private AudioTranslationSegment(@JsonProperty(value = "id") int id, @JsonProperty(value = "start") double start, - @JsonProperty(value = "end") double end, @JsonProperty(value = "text") String text, - @JsonProperty(value = "temperature") double temperature, @JsonProperty(value = "avg_logprob") double avgLogprob, - @JsonProperty(value = "compression_ratio") double compressionRatio, - @JsonProperty(value = "no_speech_prob") double noSpeechProb, - @JsonProperty(value = "tokens") List tokens, @JsonProperty(value = "seek") int seek) { - this(id, Duration.ofNanos((long) (start * 1000_000_000L)), Duration.ofNanos((long) (end * 1000_000_000L)), text, - temperature, avgLogprob, compressionRatio, noSpeechProb, tokens, seek); - } - /** * Get the id property: The 0-based index of this segment within a translation. * @@ -245,4 +226,78 @@ public List getTokens() { public int getSeek() { return this.seek; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("id", this.id); + jsonWriter.writeDoubleField("start", this.start); + jsonWriter.writeDoubleField("end", this.end); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeDoubleField("temperature", this.temperature); + jsonWriter.writeDoubleField("avg_logprob", this.avgLogprob); + jsonWriter.writeDoubleField("compression_ratio", this.compressionRatio); + jsonWriter.writeDoubleField("no_speech_prob", this.noSpeechProb); + jsonWriter.writeArrayField("tokens", this.tokens, (writer, element) -> writer.writeInt(element)); + jsonWriter.writeIntField("seek", this.seek); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AudioTranslationSegment from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AudioTranslationSegment 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 AudioTranslationSegment. + */ + @Generated + public static AudioTranslationSegment fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + int id = 0; + Duration start = null; + Duration end = null; + String text = null; + double temperature = 0.0; + double avgLogprob = 0.0; + double compressionRatio = 0.0; + double noSpeechProb = 0.0; + List tokens = null; + int seek = 0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getInt(); + } else if ("start".equals(fieldName)) { + start = Duration.ofNanos((long) (reader.getDouble() * 1000_000_000L)); + } else if ("end".equals(fieldName)) { + end = Duration.ofNanos((long) (reader.getDouble() * 1000_000_000L)); + } else if ("text".equals(fieldName)) { + text = reader.getString(); + } else if ("temperature".equals(fieldName)) { + temperature = reader.getDouble(); + } else if ("avg_logprob".equals(fieldName)) { + avgLogprob = reader.getDouble(); + } else if ("compression_ratio".equals(fieldName)) { + compressionRatio = reader.getDouble(); + } else if ("no_speech_prob".equals(fieldName)) { + noSpeechProb = reader.getDouble(); + } else if ("tokens".equals(fieldName)) { + tokens = reader.readArray(reader1 -> reader1.getInt()); + } else if ("seek".equals(fieldName)) { + seek = reader.getInt(); + } else { + reader.skipChildren(); + } + } + return new AudioTranslationSegment(id, start, end, text, temperature, avgLogprob, compressionRatio, + noSpeechProb, tokens, seek); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatEnhancementConfiguration.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatEnhancementConfiguration.java index 5bc37634f6ed3..1b8722de55779 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatEnhancementConfiguration.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatEnhancementConfiguration.java @@ -5,26 +5,28 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A representation of the available Azure OpenAI enhancement configurations. */ @Fluent -public final class AzureChatEnhancementConfiguration { +public final class AzureChatEnhancementConfiguration implements JsonSerializable { /* * A representation of the available options for the Azure OpenAI grounding enhancement. */ @Generated - @JsonProperty(value = "grounding") private AzureChatGroundingEnhancementConfiguration grounding; /* * A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. */ @Generated - @JsonProperty(value = "ocr") private AzureChatOCREnhancementConfiguration ocr; /** @@ -79,4 +81,46 @@ public AzureChatEnhancementConfiguration setOcr(AzureChatOCREnhancementConfigura this.ocr = ocr; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("grounding", this.grounding); + jsonWriter.writeJsonField("ocr", this.ocr); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureChatEnhancementConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureChatEnhancementConfiguration if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the AzureChatEnhancementConfiguration. + */ + @Generated + public static AzureChatEnhancementConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureChatEnhancementConfiguration deserializedAzureChatEnhancementConfiguration + = new AzureChatEnhancementConfiguration(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("grounding".equals(fieldName)) { + deserializedAzureChatEnhancementConfiguration.grounding + = AzureChatGroundingEnhancementConfiguration.fromJson(reader); + } else if ("ocr".equals(fieldName)) { + deserializedAzureChatEnhancementConfiguration.ocr + = AzureChatOCREnhancementConfiguration.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedAzureChatEnhancementConfiguration; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatEnhancements.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatEnhancements.java index dfbde2cee117b..3285cd09efac0 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatEnhancements.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatEnhancements.java @@ -5,7 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Represents the output results of Azure enhancements to chat completions, as configured via the matching input @@ -13,13 +17,12 @@ * in the request. */ @Immutable -public final class AzureChatEnhancements { +public final class AzureChatEnhancements implements JsonSerializable { /* * The grounding enhancement that returns the bounding box of the objects detected in the image. */ @Generated - @JsonProperty(value = "grounding") private AzureGroundingEnhancement grounding; /** @@ -39,4 +42,40 @@ private AzureChatEnhancements() { public AzureGroundingEnhancement getGrounding() { return this.grounding; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("grounding", this.grounding); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureChatEnhancements from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureChatEnhancements if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IOException If an error occurs while reading the AzureChatEnhancements. + */ + @Generated + public static AzureChatEnhancements fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureChatEnhancements deserializedAzureChatEnhancements = new AzureChatEnhancements(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("grounding".equals(fieldName)) { + deserializedAzureChatEnhancements.grounding = AzureGroundingEnhancement.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedAzureChatEnhancements; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionConfiguration.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionConfiguration.java index 891b46e873f60..d1c705ed4a788 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionConfiguration.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionConfiguration.java @@ -5,31 +5,19 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat * completions request that should use Azure OpenAI chat extensions to augment the response behavior. * The use of this configuration is compatible only with Azure OpenAI. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = AzureChatExtensionConfiguration.class, - visible = true) -@JsonTypeName("AzureChatExtensionConfiguration") -@JsonSubTypes({ - @JsonSubTypes.Type(name = "azure_search", value = AzureSearchChatExtensionConfiguration.class), - @JsonSubTypes.Type(name = "azure_ml_index", value = AzureMachineLearningIndexChatExtensionConfiguration.class), - @JsonSubTypes.Type(name = "azure_cosmos_db", value = AzureCosmosDBChatExtensionConfiguration.class), - @JsonSubTypes.Type(name = "elasticsearch", value = ElasticsearchChatExtensionConfiguration.class), - @JsonSubTypes.Type(name = "pinecone", value = PineconeChatExtensionConfiguration.class) }) @Immutable -public class AzureChatExtensionConfiguration { +public class AzureChatExtensionConfiguration implements JsonSerializable { /** * Creates an instance of AzureChatExtensionConfiguration class. @@ -44,8 +32,6 @@ public AzureChatExtensionConfiguration() { * Azure chat extensions are only compatible with Azure OpenAI. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private AzureChatExtensionType type; /** @@ -59,4 +45,77 @@ public AzureChatExtensionConfiguration() { public AzureChatExtensionType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureChatExtensionConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureChatExtensionConfiguration if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the AzureChatExtensionConfiguration. + */ + @Generated + public static AzureChatExtensionConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("azure_search".equals(discriminatorValue)) { + return AzureSearchChatExtensionConfiguration.fromJson(readerToUse.reset()); + } else if ("azure_ml_index".equals(discriminatorValue)) { + return AzureMachineLearningIndexChatExtensionConfiguration.fromJson(readerToUse.reset()); + } else if ("azure_cosmos_db".equals(discriminatorValue)) { + return AzureCosmosDBChatExtensionConfiguration.fromJson(readerToUse.reset()); + } else if ("elasticsearch".equals(discriminatorValue)) { + return ElasticsearchChatExtensionConfiguration.fromJson(readerToUse.reset()); + } else if ("pinecone".equals(discriminatorValue)) { + return PineconeChatExtensionConfiguration.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static AzureChatExtensionConfiguration fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureChatExtensionConfiguration deserializedAzureChatExtensionConfiguration + = new AzureChatExtensionConfiguration(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedAzureChatExtensionConfiguration.type + = AzureChatExtensionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedAzureChatExtensionConfiguration; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionDataSourceResponseCitation.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionDataSourceResponseCitation.java index c8eb0c7c7a305..56a0763102343 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionDataSourceResponseCitation.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionDataSourceResponseCitation.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A single instance of additional context information available when Azure OpenAI chat extensions are involved @@ -14,41 +17,37 @@ * using an Azure OpenAI request configured to use a matching extension. */ @Immutable -public final class AzureChatExtensionDataSourceResponseCitation { +public final class AzureChatExtensionDataSourceResponseCitation + implements JsonSerializable { /* * The content of the citation. */ @Generated - @JsonProperty(value = "content") private final String content; /* * The title of the citation. */ @Generated - @JsonProperty(value = "title") private String title; /* * The URL of the citation. */ @Generated - @JsonProperty(value = "url") private String url; /* * The file path of the citation. */ @Generated - @JsonProperty(value = "filepath") private String filepath; /* * The chunk ID of the citation. */ @Generated - @JsonProperty(value = "chunk_id") private String chunkId; /** @@ -57,8 +56,7 @@ public final class AzureChatExtensionDataSourceResponseCitation { * @param content the content value to set. */ @Generated - @JsonCreator - private AzureChatExtensionDataSourceResponseCitation(@JsonProperty(value = "content") String content) { + private AzureChatExtensionDataSourceResponseCitation(String content) { this.content = content; } @@ -111,4 +109,63 @@ public String getFilepath() { public String getChunkId() { return this.chunkId; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("content", this.content); + jsonWriter.writeStringField("title", this.title); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("filepath", this.filepath); + jsonWriter.writeStringField("chunk_id", this.chunkId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureChatExtensionDataSourceResponseCitation from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureChatExtensionDataSourceResponseCitation 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 AzureChatExtensionDataSourceResponseCitation. + */ + @Generated + public static AzureChatExtensionDataSourceResponseCitation fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String content = null; + String title = null; + String url = null; + String filepath = null; + String chunkId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("content".equals(fieldName)) { + content = reader.getString(); + } else if ("title".equals(fieldName)) { + title = reader.getString(); + } else if ("url".equals(fieldName)) { + url = reader.getString(); + } else if ("filepath".equals(fieldName)) { + filepath = reader.getString(); + } else if ("chunk_id".equals(fieldName)) { + chunkId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AzureChatExtensionDataSourceResponseCitation deserializedAzureChatExtensionDataSourceResponseCitation + = new AzureChatExtensionDataSourceResponseCitation(content); + deserializedAzureChatExtensionDataSourceResponseCitation.title = title; + deserializedAzureChatExtensionDataSourceResponseCitation.url = url; + deserializedAzureChatExtensionDataSourceResponseCitation.filepath = filepath; + deserializedAzureChatExtensionDataSourceResponseCitation.chunkId = chunkId; + return deserializedAzureChatExtensionDataSourceResponseCitation; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionType.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionType.java index 9a8e975f47175..ea304cb58ef08 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionType.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionType.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -62,7 +61,6 @@ public AzureChatExtensionType() { * @return the corresponding AzureChatExtensionType. */ @Generated - @JsonCreator public static AzureChatExtensionType fromString(String name) { return fromString(name, AzureChatExtensionType.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionsMessageContext.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionsMessageContext.java index 84ffb90cbc60a..a1a4337e16e90 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionsMessageContext.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatExtensionsMessageContext.java @@ -5,7 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** @@ -14,7 +18,7 @@ * using an Azure OpenAI request configured to use a matching extension. */ @Immutable -public final class AzureChatExtensionsMessageContext { +public final class AzureChatExtensionsMessageContext implements JsonSerializable { /** * Creates an instance of AzureChatExtensionsMessageContext class. @@ -30,14 +34,12 @@ private AzureChatExtensionsMessageContext() { * extensions. */ @Generated - @JsonProperty(value = "citations") private List citations; /* * The detected intent from the chat history, used to pass to the next turn to carry over the context. */ @Generated - @JsonProperty(value = "intent") private String intent; /** @@ -64,4 +66,46 @@ public List getCitations() { public String getIntent() { return this.intent; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("citations", this.citations, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("intent", this.intent); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureChatExtensionsMessageContext from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureChatExtensionsMessageContext if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the AzureChatExtensionsMessageContext. + */ + @Generated + public static AzureChatExtensionsMessageContext fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureChatExtensionsMessageContext deserializedAzureChatExtensionsMessageContext + = new AzureChatExtensionsMessageContext(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("citations".equals(fieldName)) { + List citations + = reader.readArray(reader1 -> AzureChatExtensionDataSourceResponseCitation.fromJson(reader1)); + deserializedAzureChatExtensionsMessageContext.citations = citations; + } else if ("intent".equals(fieldName)) { + deserializedAzureChatExtensionsMessageContext.intent = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedAzureChatExtensionsMessageContext; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatGroundingEnhancementConfiguration.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatGroundingEnhancementConfiguration.java index 4f8ed8c044de0..d6c42ecd793f1 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatGroundingEnhancementConfiguration.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatGroundingEnhancementConfiguration.java @@ -5,20 +5,23 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A representation of the available options for the Azure OpenAI grounding enhancement. */ @Immutable -public final class AzureChatGroundingEnhancementConfiguration { +public final class AzureChatGroundingEnhancementConfiguration + implements JsonSerializable { /* * Specifies whether the enhancement is enabled. */ @Generated - @JsonProperty(value = "enabled") private final boolean enabled; /** @@ -27,8 +30,7 @@ public final class AzureChatGroundingEnhancementConfiguration { * @param enabled the enabled value to set. */ @Generated - @JsonCreator - public AzureChatGroundingEnhancementConfiguration(@JsonProperty(value = "enabled") boolean enabled) { + public AzureChatGroundingEnhancementConfiguration(boolean enabled) { this.enabled = enabled; } @@ -41,4 +43,41 @@ public AzureChatGroundingEnhancementConfiguration(@JsonProperty(value = "enabled public boolean isEnabled() { return this.enabled; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("enabled", this.enabled); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureChatGroundingEnhancementConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureChatGroundingEnhancementConfiguration 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 AzureChatGroundingEnhancementConfiguration. + */ + @Generated + public static AzureChatGroundingEnhancementConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean enabled = false; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("enabled".equals(fieldName)) { + enabled = reader.getBoolean(); + } else { + reader.skipChildren(); + } + } + return new AzureChatGroundingEnhancementConfiguration(enabled); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatOCREnhancementConfiguration.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatOCREnhancementConfiguration.java index 4abff19de85a8..60b7545763bf5 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatOCREnhancementConfiguration.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureChatOCREnhancementConfiguration.java @@ -5,20 +5,23 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. */ @Immutable -public final class AzureChatOCREnhancementConfiguration { +public final class AzureChatOCREnhancementConfiguration + implements JsonSerializable { /* * Specifies whether the enhancement is enabled. */ @Generated - @JsonProperty(value = "enabled") private final boolean enabled; /** @@ -27,8 +30,7 @@ public final class AzureChatOCREnhancementConfiguration { * @param enabled the enabled value to set. */ @Generated - @JsonCreator - public AzureChatOCREnhancementConfiguration(@JsonProperty(value = "enabled") boolean enabled) { + public AzureChatOCREnhancementConfiguration(boolean enabled) { this.enabled = enabled; } @@ -41,4 +43,41 @@ public AzureChatOCREnhancementConfiguration(@JsonProperty(value = "enabled") boo public boolean isEnabled() { return this.enabled; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("enabled", this.enabled); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureChatOCREnhancementConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureChatOCREnhancementConfiguration 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 AzureChatOCREnhancementConfiguration. + */ + @Generated + public static AzureChatOCREnhancementConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean enabled = false; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("enabled".equals(fieldName)) { + enabled = reader.getBoolean(); + } else { + reader.skipChildren(); + } + } + return new AzureChatOCREnhancementConfiguration(enabled); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBChatExtensionConfiguration.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBChatExtensionConfiguration.java index e26511e5ee81a..33c9feaf12346 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBChatExtensionConfiguration.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBChatExtensionConfiguration.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A specific representation of configurable options for Azure Cosmos DB when using it as an Azure OpenAI chat * extension. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = AzureCosmosDBChatExtensionConfiguration.class, - visible = true) -@JsonTypeName("azure_cosmos_db") @Immutable public final class AzureCosmosDBChatExtensionConfiguration extends AzureChatExtensionConfiguration { @@ -28,7 +21,6 @@ public final class AzureCosmosDBChatExtensionConfiguration extends AzureChatExte * The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. */ @Generated - @JsonProperty(value = "parameters") private final AzureCosmosDBChatExtensionParameters parameters; /** @@ -47,9 +39,7 @@ public AzureCosmosDBChatExtensionParameters getParameters() { * @param parameters the parameters value to set. */ @Generated - @JsonCreator - public AzureCosmosDBChatExtensionConfiguration( - @JsonProperty(value = "parameters") AzureCosmosDBChatExtensionParameters parameters) { + public AzureCosmosDBChatExtensionConfiguration(AzureCosmosDBChatExtensionParameters parameters) { this.parameters = parameters; } @@ -58,8 +48,6 @@ public AzureCosmosDBChatExtensionConfiguration( * Azure chat extensions are only compatible with Azure OpenAI. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private AzureChatExtensionType type = AzureChatExtensionType.AZURE_COSMOS_DB; /** @@ -74,4 +62,48 @@ public AzureCosmosDBChatExtensionConfiguration( public AzureChatExtensionType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("parameters", this.parameters); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureCosmosDBChatExtensionConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureCosmosDBChatExtensionConfiguration 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 AzureCosmosDBChatExtensionConfiguration. + */ + @Generated + public static AzureCosmosDBChatExtensionConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureCosmosDBChatExtensionParameters parameters = null; + AzureChatExtensionType type = AzureChatExtensionType.AZURE_COSMOS_DB; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("parameters".equals(fieldName)) { + parameters = AzureCosmosDBChatExtensionParameters.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = AzureChatExtensionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + AzureCosmosDBChatExtensionConfiguration deserializedAzureCosmosDBChatExtensionConfiguration + = new AzureCosmosDBChatExtensionConfiguration(parameters); + deserializedAzureCosmosDBChatExtensionConfiguration.type = type; + return deserializedAzureCosmosDBChatExtensionConfiguration; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBChatExtensionParameters.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBChatExtensionParameters.java index 2b1fff6936eb3..38aad504f7543 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBChatExtensionParameters.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBChatExtensionParameters.java @@ -5,15 +5,19 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Parameters to use when configuring Azure OpenAI On Your Data chat extensions when using Azure Cosmos DB for * MongoDB vCore. The supported authentication type is ConnectionString. */ @Fluent -public final class AzureCosmosDBChatExtensionParameters { +public final class AzureCosmosDBChatExtensionParameters + implements JsonSerializable { /* * The authentication method to use when accessing the defined data source. @@ -23,70 +27,60 @@ public final class AzureCosmosDBChatExtensionParameters { * authentication. */ @Generated - @JsonProperty(value = "authentication") private OnYourDataAuthenticationOptions authentication; /* * The configured top number of documents to feature for the configured query. */ @Generated - @JsonProperty(value = "top_n_documents") private Integer topNDocuments; /* * Whether queries should be restricted to use of indexed data. */ @Generated - @JsonProperty(value = "in_scope") private Boolean inScope; /* * The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ @Generated - @JsonProperty(value = "strictness") private Integer strictness; /* * Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ @Generated - @JsonProperty(value = "role_information") private String roleInformation; /* * The MongoDB vCore database name to use with Azure Cosmos DB. */ @Generated - @JsonProperty(value = "database_name") private final String databaseName; /* * The name of the Azure Cosmos DB resource container. */ @Generated - @JsonProperty(value = "container_name") private final String containerName; /* * The MongoDB vCore index name to use with Azure Cosmos DB. */ @Generated - @JsonProperty(value = "index_name") private final String indexName; /* * Customized field mapping behavior to use when interacting with the search index. */ @Generated - @JsonProperty(value = "fields_mapping") private final AzureCosmosDBFieldMappingOptions fieldsMapping; /* * The embedding dependency for vector search. */ @Generated - @JsonProperty(value = "embedding_dependency") private final OnYourDataVectorizationSource embeddingDependency; /** @@ -275,16 +269,93 @@ public OnYourDataVectorizationSource getEmbeddingDependency() { * @param embeddingDependency the embeddingDependency value to set. */ @Generated - @JsonCreator - public AzureCosmosDBChatExtensionParameters(@JsonProperty(value = "database_name") String databaseName, - @JsonProperty(value = "container_name") String containerName, - @JsonProperty(value = "index_name") String indexName, - @JsonProperty(value = "fields_mapping") AzureCosmosDBFieldMappingOptions fieldsMapping, - @JsonProperty(value = "embedding_dependency") OnYourDataVectorizationSource embeddingDependency) { + public AzureCosmosDBChatExtensionParameters(String databaseName, String containerName, String indexName, + AzureCosmosDBFieldMappingOptions fieldsMapping, OnYourDataVectorizationSource embeddingDependency) { this.databaseName = databaseName; this.containerName = containerName; this.indexName = indexName; this.fieldsMapping = fieldsMapping; this.embeddingDependency = embeddingDependency; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("database_name", this.databaseName); + jsonWriter.writeStringField("container_name", this.containerName); + jsonWriter.writeStringField("index_name", this.indexName); + jsonWriter.writeJsonField("fields_mapping", this.fieldsMapping); + jsonWriter.writeJsonField("embedding_dependency", this.embeddingDependency); + jsonWriter.writeJsonField("authentication", this.authentication); + jsonWriter.writeNumberField("top_n_documents", this.topNDocuments); + jsonWriter.writeBooleanField("in_scope", this.inScope); + jsonWriter.writeNumberField("strictness", this.strictness); + jsonWriter.writeStringField("role_information", this.roleInformation); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureCosmosDBChatExtensionParameters from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureCosmosDBChatExtensionParameters 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 AzureCosmosDBChatExtensionParameters. + */ + @Generated + public static AzureCosmosDBChatExtensionParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String databaseName = null; + String containerName = null; + String indexName = null; + AzureCosmosDBFieldMappingOptions fieldsMapping = null; + OnYourDataVectorizationSource embeddingDependency = null; + OnYourDataAuthenticationOptions authentication = null; + Integer topNDocuments = null; + Boolean inScope = null; + Integer strictness = null; + String roleInformation = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("database_name".equals(fieldName)) { + databaseName = reader.getString(); + } else if ("container_name".equals(fieldName)) { + containerName = reader.getString(); + } else if ("index_name".equals(fieldName)) { + indexName = reader.getString(); + } else if ("fields_mapping".equals(fieldName)) { + fieldsMapping = AzureCosmosDBFieldMappingOptions.fromJson(reader); + } else if ("embedding_dependency".equals(fieldName)) { + embeddingDependency = OnYourDataVectorizationSource.fromJson(reader); + } else if ("authentication".equals(fieldName)) { + authentication = OnYourDataAuthenticationOptions.fromJson(reader); + } else if ("top_n_documents".equals(fieldName)) { + topNDocuments = reader.getNullable(JsonReader::getInt); + } else if ("in_scope".equals(fieldName)) { + inScope = reader.getNullable(JsonReader::getBoolean); + } else if ("strictness".equals(fieldName)) { + strictness = reader.getNullable(JsonReader::getInt); + } else if ("role_information".equals(fieldName)) { + roleInformation = reader.getString(); + } else { + reader.skipChildren(); + } + } + AzureCosmosDBChatExtensionParameters deserializedAzureCosmosDBChatExtensionParameters + = new AzureCosmosDBChatExtensionParameters(databaseName, containerName, indexName, fieldsMapping, + embeddingDependency); + deserializedAzureCosmosDBChatExtensionParameters.authentication = authentication; + deserializedAzureCosmosDBChatExtensionParameters.topNDocuments = topNDocuments; + deserializedAzureCosmosDBChatExtensionParameters.inScope = inScope; + deserializedAzureCosmosDBChatExtensionParameters.strictness = strictness; + deserializedAzureCosmosDBChatExtensionParameters.roleInformation = roleInformation; + return deserializedAzureCosmosDBChatExtensionParameters; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBFieldMappingOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBFieldMappingOptions.java index ac0d3f6376dc3..b49ce112982ab 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBFieldMappingOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureCosmosDBFieldMappingOptions.java @@ -5,21 +5,23 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * Optional settings to control how fields are processed when using a configured Azure Cosmos DB resource. */ @Fluent -public final class AzureCosmosDBFieldMappingOptions { +public final class AzureCosmosDBFieldMappingOptions implements JsonSerializable { /* * The names of fields that represent vector data. */ @Generated - @JsonProperty(value = "vector_fields") private final List vectorFields; /** @@ -36,35 +38,30 @@ public List getVectorFields() { * The name of the index field to use as a title. */ @Generated - @JsonProperty(value = "title_field") private String titleField; /* * The name of the index field to use as a URL. */ @Generated - @JsonProperty(value = "url_field") private String urlField; /* * The name of the index field to use as a filepath. */ @Generated - @JsonProperty(value = "filepath_field") private String filepathField; /* * The names of index fields that should be treated as content. */ @Generated - @JsonProperty(value = "content_fields") private final List contentFields; /* * The separator pattern that content fields should use. */ @Generated - @JsonProperty(value = "content_fields_separator") private String contentFieldsSeparator; /** @@ -74,9 +71,7 @@ public List getVectorFields() { * @param vectorFields the vectorFields value to set. */ @Generated - @JsonCreator - public AzureCosmosDBFieldMappingOptions(@JsonProperty(value = "content_fields") List contentFields, - @JsonProperty(value = "vector_fields") List vectorFields) { + public AzureCosmosDBFieldMappingOptions(List contentFields, List vectorFields) { this.contentFields = contentFields; this.vectorFields = vectorFields; } @@ -178,4 +173,69 @@ public AzureCosmosDBFieldMappingOptions setContentFieldsSeparator(String content this.contentFieldsSeparator = contentFieldsSeparator; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("content_fields", this.contentFields, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("vector_fields", this.vectorFields, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("title_field", this.titleField); + jsonWriter.writeStringField("url_field", this.urlField); + jsonWriter.writeStringField("filepath_field", this.filepathField); + jsonWriter.writeStringField("content_fields_separator", this.contentFieldsSeparator); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureCosmosDBFieldMappingOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureCosmosDBFieldMappingOptions 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 AzureCosmosDBFieldMappingOptions. + */ + @Generated + public static AzureCosmosDBFieldMappingOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List contentFields = null; + List vectorFields = null; + String titleField = null; + String urlField = null; + String filepathField = null; + String contentFieldsSeparator = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("content_fields".equals(fieldName)) { + contentFields = reader.readArray(reader1 -> reader1.getString()); + } else if ("vector_fields".equals(fieldName)) { + vectorFields = reader.readArray(reader1 -> reader1.getString()); + } else if ("title_field".equals(fieldName)) { + titleField = reader.getString(); + } else if ("url_field".equals(fieldName)) { + urlField = reader.getString(); + } else if ("filepath_field".equals(fieldName)) { + filepathField = reader.getString(); + } else if ("content_fields_separator".equals(fieldName)) { + contentFieldsSeparator = reader.getString(); + } else { + reader.skipChildren(); + } + } + AzureCosmosDBFieldMappingOptions deserializedAzureCosmosDBFieldMappingOptions + = new AzureCosmosDBFieldMappingOptions(contentFields, vectorFields); + deserializedAzureCosmosDBFieldMappingOptions.titleField = titleField; + deserializedAzureCosmosDBFieldMappingOptions.urlField = urlField; + deserializedAzureCosmosDBFieldMappingOptions.filepathField = filepathField; + deserializedAzureCosmosDBFieldMappingOptions.contentFieldsSeparator = contentFieldsSeparator; + return deserializedAzureCosmosDBFieldMappingOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancement.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancement.java index 5d3c90b7a856b..abe2a17309b08 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancement.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancement.java @@ -5,21 +5,23 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * The grounding enhancement that returns the bounding box of the objects detected in the image. */ @Immutable -public final class AzureGroundingEnhancement { +public final class AzureGroundingEnhancement implements JsonSerializable { /* * The lines of text detected by the grounding enhancement. */ @Generated - @JsonProperty(value = "lines") private final List lines; /** @@ -28,8 +30,7 @@ public final class AzureGroundingEnhancement { * @param lines the lines value to set. */ @Generated - @JsonCreator - private AzureGroundingEnhancement(@JsonProperty(value = "lines") List lines) { + private AzureGroundingEnhancement(List lines) { this.lines = lines; } @@ -42,4 +43,41 @@ private AzureGroundingEnhancement(@JsonProperty(value = "lines") List getLines() { return this.lines; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("lines", this.lines, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureGroundingEnhancement from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureGroundingEnhancement 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 AzureGroundingEnhancement. + */ + @Generated + public static AzureGroundingEnhancement fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List lines = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("lines".equals(fieldName)) { + lines = reader.readArray(reader1 -> AzureGroundingEnhancementLine.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + return new AzureGroundingEnhancement(lines); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementCoordinatePoint.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementCoordinatePoint.java index dc90a0ca9b3d4..e320b9acb87fa 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementCoordinatePoint.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementCoordinatePoint.java @@ -5,27 +5,29 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A representation of a single polygon point as used by the Azure grounding enhancement. */ @Immutable -public final class AzureGroundingEnhancementCoordinatePoint { +public final class AzureGroundingEnhancementCoordinatePoint + implements JsonSerializable { /* * The x-coordinate (horizontal axis) of the point. */ @Generated - @JsonProperty(value = "x") private final double x; /* * The y-coordinate (vertical axis) of the point. */ @Generated - @JsonProperty(value = "y") private final double y; /** @@ -35,9 +37,7 @@ public final class AzureGroundingEnhancementCoordinatePoint { * @param y the y value to set. */ @Generated - @JsonCreator - private AzureGroundingEnhancementCoordinatePoint(@JsonProperty(value = "x") double x, - @JsonProperty(value = "y") double y) { + private AzureGroundingEnhancementCoordinatePoint(double x, double y) { this.x = x; this.y = y; } @@ -61,4 +61,45 @@ public double getX() { public double getY() { return this.y; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeDoubleField("x", this.x); + jsonWriter.writeDoubleField("y", this.y); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureGroundingEnhancementCoordinatePoint from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureGroundingEnhancementCoordinatePoint 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 AzureGroundingEnhancementCoordinatePoint. + */ + @Generated + public static AzureGroundingEnhancementCoordinatePoint fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + double x = 0.0; + double y = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("x".equals(fieldName)) { + x = reader.getDouble(); + } else if ("y".equals(fieldName)) { + y = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new AzureGroundingEnhancementCoordinatePoint(x, y); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementLine.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementLine.java index 71f31f36eae2f..ee30eeb6bbcbd 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementLine.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementLine.java @@ -5,28 +5,29 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * A content line object consisting of an adjacent sequence of content elements, such as words and selection marks. */ @Immutable -public final class AzureGroundingEnhancementLine { +public final class AzureGroundingEnhancementLine implements JsonSerializable { /* * The text within the line. */ @Generated - @JsonProperty(value = "text") private final String text; /* * An array of spans that represent detected objects and its bounding box information. */ @Generated - @JsonProperty(value = "spans") private final List spans; /** @@ -36,9 +37,7 @@ public final class AzureGroundingEnhancementLine { * @param spans the spans value to set. */ @Generated - @JsonCreator - private AzureGroundingEnhancementLine(@JsonProperty(value = "text") String text, - @JsonProperty(value = "spans") List spans) { + private AzureGroundingEnhancementLine(String text, List spans) { this.text = text; this.spans = spans; } @@ -62,4 +61,45 @@ public String getText() { public List getSpans() { return this.spans; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeArrayField("spans", this.spans, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureGroundingEnhancementLine from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureGroundingEnhancementLine 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 AzureGroundingEnhancementLine. + */ + @Generated + public static AzureGroundingEnhancementLine fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String text = null; + List spans = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("text".equals(fieldName)) { + text = reader.getString(); + } else if ("spans".equals(fieldName)) { + spans = reader.readArray(reader1 -> AzureGroundingEnhancementLineSpan.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + return new AzureGroundingEnhancementLine(text, spans); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementLineSpan.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementLineSpan.java index 20271a3d69c5a..4cac9cac159a1 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementLineSpan.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureGroundingEnhancementLineSpan.java @@ -5,21 +5,23 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * A span object that represents a detected object and its bounding box information. */ @Immutable -public final class AzureGroundingEnhancementLineSpan { +public final class AzureGroundingEnhancementLineSpan implements JsonSerializable { /* * The text content of the span that represents the detected object. */ @Generated - @JsonProperty(value = "text") private final String text; /* @@ -27,21 +29,18 @@ public final class AzureGroundingEnhancementLineSpan { * character of the span, counting from the start of the text as Unicode codepoints. */ @Generated - @JsonProperty(value = "offset") private final int offset; /* * The length of the span in characters, measured in Unicode codepoints. */ @Generated - @JsonProperty(value = "length") private final int length; /* * An array of objects representing points in the polygon that encloses the detected object. */ @Generated - @JsonProperty(value = "polygon") private final List polygon; /** @@ -53,10 +52,8 @@ public final class AzureGroundingEnhancementLineSpan { * @param polygon the polygon value to set. */ @Generated - @JsonCreator - private AzureGroundingEnhancementLineSpan(@JsonProperty(value = "text") String text, - @JsonProperty(value = "offset") int offset, @JsonProperty(value = "length") int length, - @JsonProperty(value = "polygon") List polygon) { + private AzureGroundingEnhancementLineSpan(String text, int offset, int length, + List polygon) { this.text = text; this.offset = offset; this.length = length; @@ -105,4 +102,53 @@ public int getLength() { public List getPolygon() { return this.polygon; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeIntField("offset", this.offset); + jsonWriter.writeIntField("length", this.length); + jsonWriter.writeArrayField("polygon", this.polygon, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureGroundingEnhancementLineSpan from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureGroundingEnhancementLineSpan 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 AzureGroundingEnhancementLineSpan. + */ + @Generated + public static AzureGroundingEnhancementLineSpan fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String text = null; + int offset = 0; + int length = 0; + List polygon = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("text".equals(fieldName)) { + text = reader.getString(); + } else if ("offset".equals(fieldName)) { + offset = reader.getInt(); + } else if ("length".equals(fieldName)) { + length = reader.getInt(); + } else if ("polygon".equals(fieldName)) { + polygon = reader.readArray(reader1 -> AzureGroundingEnhancementCoordinatePoint.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + return new AzureGroundingEnhancementLineSpan(text, offset, length, polygon); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureMachineLearningIndexChatExtensionConfiguration.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureMachineLearningIndexChatExtensionConfiguration.java index 11819655d5bd7..e078f57f6e60c 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureMachineLearningIndexChatExtensionConfiguration.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureMachineLearningIndexChatExtensionConfiguration.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A specific representation of configurable options for Azure Machine Learning vector index when using it as an Azure * OpenAI chat extension. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = AzureMachineLearningIndexChatExtensionConfiguration.class, - visible = true) -@JsonTypeName("azure_ml_index") @Immutable public final class AzureMachineLearningIndexChatExtensionConfiguration extends AzureChatExtensionConfiguration { @@ -28,7 +21,6 @@ public final class AzureMachineLearningIndexChatExtensionConfiguration extends A * The parameters for the Azure Machine Learning vector index chat extension. */ @Generated - @JsonProperty(value = "parameters") private final AzureMachineLearningIndexChatExtensionParameters parameters; /** @@ -47,9 +39,8 @@ public AzureMachineLearningIndexChatExtensionParameters getParameters() { * @param parameters the parameters value to set. */ @Generated - @JsonCreator public AzureMachineLearningIndexChatExtensionConfiguration( - @JsonProperty(value = "parameters") AzureMachineLearningIndexChatExtensionParameters parameters) { + AzureMachineLearningIndexChatExtensionParameters parameters) { this.parameters = parameters; } @@ -58,8 +49,6 @@ public AzureMachineLearningIndexChatExtensionConfiguration( * Azure chat extensions are only compatible with Azure OpenAI. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private AzureChatExtensionType type = AzureChatExtensionType.AZURE_MACHINE_LEARNING_INDEX; /** @@ -74,4 +63,49 @@ public AzureMachineLearningIndexChatExtensionConfiguration( public AzureChatExtensionType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("parameters", this.parameters); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureMachineLearningIndexChatExtensionConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureMachineLearningIndexChatExtensionConfiguration 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 AzureMachineLearningIndexChatExtensionConfiguration. + */ + @Generated + public static AzureMachineLearningIndexChatExtensionConfiguration fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + AzureMachineLearningIndexChatExtensionParameters parameters = null; + AzureChatExtensionType type = AzureChatExtensionType.AZURE_MACHINE_LEARNING_INDEX; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("parameters".equals(fieldName)) { + parameters = AzureMachineLearningIndexChatExtensionParameters.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = AzureChatExtensionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + AzureMachineLearningIndexChatExtensionConfiguration deserializedAzureMachineLearningIndexChatExtensionConfiguration + = new AzureMachineLearningIndexChatExtensionConfiguration(parameters); + deserializedAzureMachineLearningIndexChatExtensionConfiguration.type = type; + return deserializedAzureMachineLearningIndexChatExtensionConfiguration; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureMachineLearningIndexChatExtensionParameters.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureMachineLearningIndexChatExtensionParameters.java index 1d5f49135d6d6..e90bd76cc46a5 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureMachineLearningIndexChatExtensionParameters.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureMachineLearningIndexChatExtensionParameters.java @@ -5,15 +5,19 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Parameters for the Azure Machine Learning vector index chat extension. The supported authentication types are * AccessToken, SystemAssignedManagedIdentity and UserAssignedManagedIdentity. */ @Fluent -public final class AzureMachineLearningIndexChatExtensionParameters { +public final class AzureMachineLearningIndexChatExtensionParameters + implements JsonSerializable { /* * The authentication method to use when accessing the defined data source. @@ -23,63 +27,54 @@ public final class AzureMachineLearningIndexChatExtensionParameters { * authentication. */ @Generated - @JsonProperty(value = "authentication") private OnYourDataAuthenticationOptions authentication; /* * The configured top number of documents to feature for the configured query. */ @Generated - @JsonProperty(value = "top_n_documents") private Integer topNDocuments; /* * Whether queries should be restricted to use of indexed data. */ @Generated - @JsonProperty(value = "in_scope") private Boolean inScope; /* * The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ @Generated - @JsonProperty(value = "strictness") private Integer strictness; /* * Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ @Generated - @JsonProperty(value = "role_information") private String roleInformation; /* * The resource ID of the Azure Machine Learning project. */ @Generated - @JsonProperty(value = "project_resource_id") private final String projectResourceId; /* * The Azure Machine Learning vector index name. */ @Generated - @JsonProperty(value = "name") private final String name; /* * The version of the Azure Machine Learning vector index. */ @Generated - @JsonProperty(value = "version") private final String version; /* * Search filter. Only supported if the Azure Machine Learning vector index is of type AzureSearch. */ @Generated - @JsonProperty(value = "filter") private String filter; /** @@ -90,10 +85,7 @@ public final class AzureMachineLearningIndexChatExtensionParameters { * @param version the version value to set. */ @Generated - @JsonCreator - public AzureMachineLearningIndexChatExtensionParameters( - @JsonProperty(value = "project_resource_id") String projectResourceId, - @JsonProperty(value = "name") String name, @JsonProperty(value = "version") String version) { + public AzureMachineLearningIndexChatExtensionParameters(String projectResourceId, String name, String version) { this.projectResourceId = projectResourceId; this.name = name; this.version = version; @@ -279,4 +271,81 @@ public AzureMachineLearningIndexChatExtensionParameters setFilter(String filter) this.filter = filter; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("project_resource_id", this.projectResourceId); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("version", this.version); + jsonWriter.writeJsonField("authentication", this.authentication); + jsonWriter.writeNumberField("top_n_documents", this.topNDocuments); + jsonWriter.writeBooleanField("in_scope", this.inScope); + jsonWriter.writeNumberField("strictness", this.strictness); + jsonWriter.writeStringField("role_information", this.roleInformation); + jsonWriter.writeStringField("filter", this.filter); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureMachineLearningIndexChatExtensionParameters from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureMachineLearningIndexChatExtensionParameters 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 AzureMachineLearningIndexChatExtensionParameters. + */ + @Generated + public static AzureMachineLearningIndexChatExtensionParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String projectResourceId = null; + String name = null; + String version = null; + OnYourDataAuthenticationOptions authentication = null; + Integer topNDocuments = null; + Boolean inScope = null; + Integer strictness = null; + String roleInformation = null; + String filter = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("project_resource_id".equals(fieldName)) { + projectResourceId = reader.getString(); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getString(); + } else if ("authentication".equals(fieldName)) { + authentication = OnYourDataAuthenticationOptions.fromJson(reader); + } else if ("top_n_documents".equals(fieldName)) { + topNDocuments = reader.getNullable(JsonReader::getInt); + } else if ("in_scope".equals(fieldName)) { + inScope = reader.getNullable(JsonReader::getBoolean); + } else if ("strictness".equals(fieldName)) { + strictness = reader.getNullable(JsonReader::getInt); + } else if ("role_information".equals(fieldName)) { + roleInformation = reader.getString(); + } else if ("filter".equals(fieldName)) { + filter = reader.getString(); + } else { + reader.skipChildren(); + } + } + AzureMachineLearningIndexChatExtensionParameters deserializedAzureMachineLearningIndexChatExtensionParameters + = new AzureMachineLearningIndexChatExtensionParameters(projectResourceId, name, version); + deserializedAzureMachineLearningIndexChatExtensionParameters.authentication = authentication; + deserializedAzureMachineLearningIndexChatExtensionParameters.topNDocuments = topNDocuments; + deserializedAzureMachineLearningIndexChatExtensionParameters.inScope = inScope; + deserializedAzureMachineLearningIndexChatExtensionParameters.strictness = strictness; + deserializedAzureMachineLearningIndexChatExtensionParameters.roleInformation = roleInformation; + deserializedAzureMachineLearningIndexChatExtensionParameters.filter = filter; + return deserializedAzureMachineLearningIndexChatExtensionParameters; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchChatExtensionConfiguration.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchChatExtensionConfiguration.java index aab684c4c4d8a..6cdbb58c7ac9c 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchChatExtensionConfiguration.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchChatExtensionConfiguration.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A specific representation of configurable options for Azure Search when using it as an Azure OpenAI chat * extension. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = AzureSearchChatExtensionConfiguration.class, - visible = true) -@JsonTypeName("azure_search") @Immutable public final class AzureSearchChatExtensionConfiguration extends AzureChatExtensionConfiguration { @@ -28,7 +21,6 @@ public final class AzureSearchChatExtensionConfiguration extends AzureChatExtens * The parameters to use when configuring Azure Search. */ @Generated - @JsonProperty(value = "parameters") private final AzureSearchChatExtensionParameters parameters; /** @@ -37,9 +29,7 @@ public final class AzureSearchChatExtensionConfiguration extends AzureChatExtens * @param parameters the parameters value to set. */ @Generated - @JsonCreator - public AzureSearchChatExtensionConfiguration( - @JsonProperty(value = "parameters") AzureSearchChatExtensionParameters parameters) { + public AzureSearchChatExtensionConfiguration(AzureSearchChatExtensionParameters parameters) { this.parameters = parameters; } @@ -58,8 +48,6 @@ public AzureSearchChatExtensionParameters getParameters() { * Azure chat extensions are only compatible with Azure OpenAI. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private AzureChatExtensionType type = AzureChatExtensionType.AZURE_SEARCH; /** @@ -74,4 +62,48 @@ public AzureSearchChatExtensionParameters getParameters() { public AzureChatExtensionType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("parameters", this.parameters); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureSearchChatExtensionConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureSearchChatExtensionConfiguration 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 AzureSearchChatExtensionConfiguration. + */ + @Generated + public static AzureSearchChatExtensionConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureSearchChatExtensionParameters parameters = null; + AzureChatExtensionType type = AzureChatExtensionType.AZURE_SEARCH; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("parameters".equals(fieldName)) { + parameters = AzureSearchChatExtensionParameters.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = AzureChatExtensionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + AzureSearchChatExtensionConfiguration deserializedAzureSearchChatExtensionConfiguration + = new AzureSearchChatExtensionConfiguration(parameters); + deserializedAzureSearchChatExtensionConfiguration.type = type; + return deserializedAzureSearchChatExtensionConfiguration; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchChatExtensionParameters.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchChatExtensionParameters.java index 08c82260b562d..44099ce7528dd 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchChatExtensionParameters.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchChatExtensionParameters.java @@ -5,15 +5,18 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Parameters for Azure Cognitive Search when used as an Azure OpenAI chat extension. The supported authentication types * are APIKey, SystemAssignedManagedIdentity and UserAssignedManagedIdentity. */ @Fluent -public final class AzureSearchChatExtensionParameters { +public final class AzureSearchChatExtensionParameters implements JsonSerializable { /* * The authentication method to use when accessing the defined data source. @@ -23,84 +26,72 @@ public final class AzureSearchChatExtensionParameters { * authentication. */ @Generated - @JsonProperty(value = "authentication") private OnYourDataAuthenticationOptions authentication; /* * The configured top number of documents to feature for the configured query. */ @Generated - @JsonProperty(value = "top_n_documents") private Integer topNDocuments; /* * Whether queries should be restricted to use of indexed data. */ @Generated - @JsonProperty(value = "in_scope") private Boolean inScope; /* * The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ @Generated - @JsonProperty(value = "strictness") private Integer strictness; /* * Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ @Generated - @JsonProperty(value = "role_information") private String roleInformation; /* * The absolute endpoint path for the Azure Cognitive Search resource to use. */ @Generated - @JsonProperty(value = "endpoint") private final String endpoint; /* * The name of the index to use as available in the referenced Azure Cognitive Search resource. */ @Generated - @JsonProperty(value = "index_name") private final String indexName; /* * Customized field mapping behavior to use when interacting with the search index. */ @Generated - @JsonProperty(value = "fields_mapping") private AzureSearchIndexFieldMappingOptions fieldsMapping; /* * The query type to use with Azure Cognitive Search. */ @Generated - @JsonProperty(value = "query_type") private AzureSearchQueryType queryType; /* * The additional semantic configuration for the query. */ @Generated - @JsonProperty(value = "semantic_configuration") private String semanticConfiguration; /* * Search filter. */ @Generated - @JsonProperty(value = "filter") private String filter; /* * The embedding dependency for vector search. */ @Generated - @JsonProperty(value = "embedding_dependency") private OnYourDataVectorizationSource embeddingDependency; /** @@ -110,9 +101,7 @@ public final class AzureSearchChatExtensionParameters { * @param indexName the indexName value to set. */ @Generated - @JsonCreator - public AzureSearchChatExtensionParameters(@JsonProperty(value = "endpoint") String endpoint, - @JsonProperty(value = "index_name") String indexName) { + public AzureSearchChatExtensionParameters(String endpoint, String indexName) { this.endpoint = endpoint; this.indexName = indexName; } @@ -374,4 +363,97 @@ public OnYourDataVectorizationSource getEmbeddingDependency() { this.embeddingDependency = embeddingDependency; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("endpoint", this.endpoint); + jsonWriter.writeStringField("index_name", this.indexName); + jsonWriter.writeJsonField("authentication", this.authentication); + jsonWriter.writeNumberField("top_n_documents", this.topNDocuments); + jsonWriter.writeBooleanField("in_scope", this.inScope); + jsonWriter.writeNumberField("strictness", this.strictness); + jsonWriter.writeStringField("role_information", this.roleInformation); + jsonWriter.writeJsonField("fields_mapping", this.fieldsMapping); + jsonWriter.writeStringField("query_type", this.queryType == null ? null : this.queryType.toString()); + jsonWriter.writeStringField("semantic_configuration", this.semanticConfiguration); + jsonWriter.writeStringField("filter", this.filter); + jsonWriter.writeJsonField("embedding_dependency", this.embeddingDependency); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureSearchChatExtensionParameters from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureSearchChatExtensionParameters 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 AzureSearchChatExtensionParameters. + */ + @Generated + public static AzureSearchChatExtensionParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String endpoint = null; + String indexName = null; + OnYourDataAuthenticationOptions authentication = null; + Integer topNDocuments = null; + Boolean inScope = null; + Integer strictness = null; + String roleInformation = null; + AzureSearchIndexFieldMappingOptions fieldsMapping = null; + AzureSearchQueryType queryType = null; + String semanticConfiguration = null; + String filter = null; + OnYourDataVectorizationSource embeddingDependency = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("endpoint".equals(fieldName)) { + endpoint = reader.getString(); + } else if ("index_name".equals(fieldName)) { + indexName = reader.getString(); + } else if ("authentication".equals(fieldName)) { + authentication = OnYourDataAuthenticationOptions.fromJson(reader); + } else if ("top_n_documents".equals(fieldName)) { + topNDocuments = reader.getNullable(JsonReader::getInt); + } else if ("in_scope".equals(fieldName)) { + inScope = reader.getNullable(JsonReader::getBoolean); + } else if ("strictness".equals(fieldName)) { + strictness = reader.getNullable(JsonReader::getInt); + } else if ("role_information".equals(fieldName)) { + roleInformation = reader.getString(); + } else if ("fields_mapping".equals(fieldName)) { + fieldsMapping = AzureSearchIndexFieldMappingOptions.fromJson(reader); + } else if ("query_type".equals(fieldName)) { + queryType = AzureSearchQueryType.fromString(reader.getString()); + } else if ("semantic_configuration".equals(fieldName)) { + semanticConfiguration = reader.getString(); + } else if ("filter".equals(fieldName)) { + filter = reader.getString(); + } else if ("embedding_dependency".equals(fieldName)) { + embeddingDependency = OnYourDataVectorizationSource.fromJson(reader); + } else { + reader.skipChildren(); + } + } + AzureSearchChatExtensionParameters deserializedAzureSearchChatExtensionParameters + = new AzureSearchChatExtensionParameters(endpoint, indexName); + deserializedAzureSearchChatExtensionParameters.authentication = authentication; + deserializedAzureSearchChatExtensionParameters.topNDocuments = topNDocuments; + deserializedAzureSearchChatExtensionParameters.inScope = inScope; + deserializedAzureSearchChatExtensionParameters.strictness = strictness; + deserializedAzureSearchChatExtensionParameters.roleInformation = roleInformation; + deserializedAzureSearchChatExtensionParameters.fieldsMapping = fieldsMapping; + deserializedAzureSearchChatExtensionParameters.queryType = queryType; + deserializedAzureSearchChatExtensionParameters.semanticConfiguration = semanticConfiguration; + deserializedAzureSearchChatExtensionParameters.filter = filter; + deserializedAzureSearchChatExtensionParameters.embeddingDependency = embeddingDependency; + return deserializedAzureSearchChatExtensionParameters; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchIndexFieldMappingOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchIndexFieldMappingOptions.java index 9c8e050b3a1ec..e56f26ad82056 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchIndexFieldMappingOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchIndexFieldMappingOptions.java @@ -5,62 +5,60 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * Optional settings to control how fields are processed when using a configured Azure Search resource. */ @Fluent -public final class AzureSearchIndexFieldMappingOptions { +public final class AzureSearchIndexFieldMappingOptions + implements JsonSerializable { /* * The name of the index field to use as a title. */ @Generated - @JsonProperty(value = "title_field") private String titleField; /* * The name of the index field to use as a URL. */ @Generated - @JsonProperty(value = "url_field") private String urlField; /* * The name of the index field to use as a filepath. */ @Generated - @JsonProperty(value = "filepath_field") private String filepathField; /* * The names of index fields that should be treated as content. */ @Generated - @JsonProperty(value = "content_fields") private List contentFields; /* * The separator pattern that content fields should use. */ @Generated - @JsonProperty(value = "content_fields_separator") private String contentFieldsSeparator; /* * The names of fields that represent vector data. */ @Generated - @JsonProperty(value = "vector_fields") private List vectorFields; /* * The names of fields that represent image vector data. */ @Generated - @JsonProperty(value = "image_vector_fields") private List imageVectorFields; /** @@ -223,4 +221,65 @@ public AzureSearchIndexFieldMappingOptions setImageVectorFields(List ima this.imageVectorFields = imageVectorFields; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("title_field", this.titleField); + jsonWriter.writeStringField("url_field", this.urlField); + jsonWriter.writeStringField("filepath_field", this.filepathField); + jsonWriter.writeArrayField("content_fields", this.contentFields, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("content_fields_separator", this.contentFieldsSeparator); + jsonWriter.writeArrayField("vector_fields", this.vectorFields, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("image_vector_fields", this.imageVectorFields, + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureSearchIndexFieldMappingOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureSearchIndexFieldMappingOptions if the JsonReader was pointing to an instance of it, + * or null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the AzureSearchIndexFieldMappingOptions. + */ + @Generated + public static AzureSearchIndexFieldMappingOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureSearchIndexFieldMappingOptions deserializedAzureSearchIndexFieldMappingOptions + = new AzureSearchIndexFieldMappingOptions(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("title_field".equals(fieldName)) { + deserializedAzureSearchIndexFieldMappingOptions.titleField = reader.getString(); + } else if ("url_field".equals(fieldName)) { + deserializedAzureSearchIndexFieldMappingOptions.urlField = reader.getString(); + } else if ("filepath_field".equals(fieldName)) { + deserializedAzureSearchIndexFieldMappingOptions.filepathField = reader.getString(); + } else if ("content_fields".equals(fieldName)) { + List contentFields = reader.readArray(reader1 -> reader1.getString()); + deserializedAzureSearchIndexFieldMappingOptions.contentFields = contentFields; + } else if ("content_fields_separator".equals(fieldName)) { + deserializedAzureSearchIndexFieldMappingOptions.contentFieldsSeparator = reader.getString(); + } else if ("vector_fields".equals(fieldName)) { + List vectorFields = reader.readArray(reader1 -> reader1.getString()); + deserializedAzureSearchIndexFieldMappingOptions.vectorFields = vectorFields; + } else if ("image_vector_fields".equals(fieldName)) { + List imageVectorFields = reader.readArray(reader1 -> reader1.getString()); + deserializedAzureSearchIndexFieldMappingOptions.imageVectorFields = imageVectorFields; + } else { + reader.skipChildren(); + } + } + return deserializedAzureSearchIndexFieldMappingOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchQueryType.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchQueryType.java index 01cfd3c9f9434..0e9f2320e898b 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchQueryType.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AzureSearchQueryType.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -60,7 +59,6 @@ public AzureSearchQueryType() { * @return the corresponding AzureSearchQueryType. */ @Generated - @JsonCreator public static AzureSearchQueryType fromString(String name) { return fromString(name, AzureSearchQueryType.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatChoice.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatChoice.java index beea975ea03c9..a7129caa4748a 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatChoice.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatChoice.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The representation of a single prompt completion as part of an overall chat completions request. @@ -14,34 +17,30 @@ * Token limits and other settings may limit the number of choices generated. */ @Immutable -public final class ChatChoice { +public final class ChatChoice implements JsonSerializable { /* * The chat message for a given chat completions prompt. */ @Generated - @JsonProperty(value = "message") private ChatResponseMessage message; /* * The ordered index associated with this chat completions choice. */ @Generated - @JsonProperty(value = "index") private final int index; /* * The reason that this chat completions choice completed its generated. */ @Generated - @JsonProperty(value = "finish_reason") private final CompletionsFinishReason finishReason; /* * The delta message content for a streaming response. */ @Generated - @JsonProperty(value = "delta") private ChatResponseMessage delta; /** @@ -90,7 +89,6 @@ public ChatResponseMessage getDelta() { * determines the intensity and risk level of harmful content) and if it has been filtered or not. */ @Generated - @JsonProperty(value = "content_filter_results") private ContentFilterResultsForChoice contentFilterResults; /** @@ -111,7 +109,6 @@ public ContentFilterResultsForChoice getContentFilterResults() { * This structured representation replaces 'finish_reason' for some models. */ @Generated - @JsonProperty(value = "finish_details") private ChatFinishDetails finishDetails; /* @@ -120,7 +117,6 @@ public ContentFilterResultsForChoice getContentFilterResults() { * request is configured to use enhancements. */ @Generated - @JsonProperty(value = "enhancements") private AzureChatEnhancements enhancements; /** @@ -153,7 +149,6 @@ public AzureChatEnhancements getEnhancements() { * The log probability information for this choice, as enabled via the 'logprobs' request option. */ @Generated - @JsonProperty(value = "logprobs") private final ChatChoiceLogProbabilityInfo logprobs; /** @@ -164,10 +159,7 @@ public AzureChatEnhancements getEnhancements() { * @param finishReason the finishReason value to set. */ @Generated - @JsonCreator - private ChatChoice(@JsonProperty(value = "logprobs") ChatChoiceLogProbabilityInfo logprobs, - @JsonProperty(value = "index") int index, - @JsonProperty(value = "finish_reason") CompletionsFinishReason finishReason) { + private ChatChoice(ChatChoiceLogProbabilityInfo logprobs, int index, CompletionsFinishReason finishReason) { this.logprobs = logprobs; this.index = index; this.finishReason = finishReason; @@ -183,4 +175,75 @@ private ChatChoice(@JsonProperty(value = "logprobs") ChatChoiceLogProbabilityInf public ChatChoiceLogProbabilityInfo getLogprobs() { return this.logprobs; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("logprobs", this.logprobs); + jsonWriter.writeIntField("index", this.index); + jsonWriter.writeStringField("finish_reason", this.finishReason == null ? null : this.finishReason.toString()); + jsonWriter.writeJsonField("message", this.message); + jsonWriter.writeJsonField("finish_details", this.finishDetails); + jsonWriter.writeJsonField("delta", this.delta); + jsonWriter.writeJsonField("content_filter_results", this.contentFilterResults); + jsonWriter.writeJsonField("enhancements", this.enhancements); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatChoice from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatChoice 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 ChatChoice. + */ + @Generated + public static ChatChoice fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatChoiceLogProbabilityInfo logprobs = null; + int index = 0; + CompletionsFinishReason finishReason = null; + ChatResponseMessage message = null; + ChatFinishDetails finishDetails = null; + ChatResponseMessage delta = null; + ContentFilterResultsForChoice contentFilterResults = null; + AzureChatEnhancements enhancements = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("logprobs".equals(fieldName)) { + logprobs = ChatChoiceLogProbabilityInfo.fromJson(reader); + } else if ("index".equals(fieldName)) { + index = reader.getInt(); + } else if ("finish_reason".equals(fieldName)) { + finishReason = CompletionsFinishReason.fromString(reader.getString()); + } else if ("message".equals(fieldName)) { + message = ChatResponseMessage.fromJson(reader); + } else if ("finish_details".equals(fieldName)) { + finishDetails = ChatFinishDetails.fromJson(reader); + } else if ("delta".equals(fieldName)) { + delta = ChatResponseMessage.fromJson(reader); + } else if ("content_filter_results".equals(fieldName)) { + contentFilterResults = ContentFilterResultsForChoice.fromJson(reader); + } else if ("enhancements".equals(fieldName)) { + enhancements = AzureChatEnhancements.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ChatChoice deserializedChatChoice = new ChatChoice(logprobs, index, finishReason); + deserializedChatChoice.message = message; + deserializedChatChoice.finishDetails = finishDetails; + deserializedChatChoice.delta = delta; + deserializedChatChoice.contentFilterResults = contentFilterResults; + deserializedChatChoice.enhancements = enhancements; + return deserializedChatChoice; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatChoiceLogProbabilityInfo.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatChoiceLogProbabilityInfo.java index 9d27e23e0c304..46256592d58d8 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatChoiceLogProbabilityInfo.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatChoiceLogProbabilityInfo.java @@ -5,21 +5,23 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * Log probability information for a choice, as requested via 'logprobs' and 'top_logprobs'. */ @Immutable -public final class ChatChoiceLogProbabilityInfo { +public final class ChatChoiceLogProbabilityInfo implements JsonSerializable { /* * The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. */ @Generated - @JsonProperty(value = "content") private final List content; /** @@ -28,8 +30,7 @@ public final class ChatChoiceLogProbabilityInfo { * @param content the content value to set. */ @Generated - @JsonCreator - private ChatChoiceLogProbabilityInfo(@JsonProperty(value = "content") List content) { + private ChatChoiceLogProbabilityInfo(List content) { this.content = content; } @@ -43,4 +44,41 @@ private ChatChoiceLogProbabilityInfo(@JsonProperty(value = "content") List getContent() { return this.content; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("content", this.content, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatChoiceLogProbabilityInfo from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatChoiceLogProbabilityInfo 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 ChatChoiceLogProbabilityInfo. + */ + @Generated + public static ChatChoiceLogProbabilityInfo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List content = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("content".equals(fieldName)) { + content = reader.readArray(reader1 -> ChatTokenLogProbabilityResult.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + return new ChatChoiceLogProbabilityInfo(content); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletions.java index 339d0173e0495..5499b9bca15a5 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletions.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -18,13 +21,12 @@ * provided prompt data. */ @Immutable -public final class ChatCompletions { +public final class ChatCompletions implements JsonSerializable { /* * A unique identifier associated with this chat completions response. */ @Generated - @JsonProperty(value = "id") private final String id; /* @@ -33,14 +35,12 @@ public final class ChatCompletions { * Token limits and other settings may limit the number of choices generated. */ @Generated - @JsonProperty(value = "choices") private final List choices; /* * Usage information for tokens processed and generated as part of this completions operation. */ @Generated - @JsonProperty(value = "usage") private final CompletionsUsage usage; /** @@ -81,7 +81,6 @@ public CompletionsUsage getUsage() { * represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. */ @Generated - @JsonProperty(value = "created") private final long createdAt; /** @@ -101,19 +100,8 @@ public OffsetDateTime getCreatedAt() { * results for different prompts may arrive at different times or in different orders. */ @Generated - @JsonProperty(value = "prompt_filter_results") private List promptFilterResults; - /** - * Backing member for the prompt filtering result during the rename transition. More details here - * - * @deprecated This field is only used for deserialization. - */ - @Deprecated - @JsonProperty(value = "prompt_annotations") - private List promptAnnotations; - /** * Get the promptFilterResults property: Content filtering results for zero or more prompts in the request. In a * streaming request, @@ -121,11 +109,9 @@ public OffsetDateTime getCreatedAt() { * * @return the promptFilterResults value. */ + @Generated public List getPromptFilterResults() { - if (this.promptFilterResults != null) { - return this.promptFilterResults; - } - return this.promptAnnotations; + return this.promptFilterResults; } /* @@ -133,7 +119,6 @@ public List getPromptFilterResults() { * might impact determinism. */ @Generated - @JsonProperty(value = "system_fingerprint") private String systemFingerprint; /** @@ -168,19 +153,10 @@ private ChatCompletions(String id, OffsetDateTime createdAt, List ch this.usage = usage; } - @Generated - @JsonCreator - private ChatCompletions(@JsonProperty(value = "id") String id, @JsonProperty(value = "created") long createdAt, - @JsonProperty(value = "choices") List choices, - @JsonProperty(value = "usage") CompletionsUsage usage) { - this(id, OffsetDateTime.ofInstant(Instant.ofEpochSecond(createdAt), ZoneOffset.UTC), choices, usage); - } - /* * The model name used for this completions request. */ @Generated - @JsonProperty(value = "model") private String model; /** @@ -192,4 +168,70 @@ private ChatCompletions(@JsonProperty(value = "id") String id, @JsonProperty(val public String getModel() { return this.model; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeLongField("created", this.createdAt); + jsonWriter.writeArrayField("choices", this.choices, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("usage", this.usage); + jsonWriter.writeStringField("model", this.model); + jsonWriter.writeArrayField("prompt_filter_results", this.promptFilterResults, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("system_fingerprint", this.systemFingerprint); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletions 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 ChatCompletions. + */ + @Generated + public static ChatCompletions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + OffsetDateTime createdAt = null; + List choices = null; + CompletionsUsage usage = null; + String model = null; + List promptFilterResults = null; + String systemFingerprint = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("created".equals(fieldName)) { + createdAt = OffsetDateTime.ofInstant(Instant.ofEpochSecond(reader.getLong()), ZoneOffset.UTC); + } else if ("choices".equals(fieldName)) { + choices = reader.readArray(reader1 -> ChatChoice.fromJson(reader1)); + } else if ("usage".equals(fieldName)) { + usage = CompletionsUsage.fromJson(reader); + } else if ("model".equals(fieldName)) { + model = reader.getString(); + } else if ("prompt_filter_results".equals(fieldName)) { + promptFilterResults = reader.readArray(reader1 -> ContentFilterResultsForPrompt.fromJson(reader1)); + } else if ("system_fingerprint".equals(fieldName)) { + systemFingerprint = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatCompletions deserializedChatCompletions = new ChatCompletions(id, createdAt, choices, usage); + deserializedChatCompletions.model = model; + deserializedChatCompletions.promptFilterResults = promptFilterResults; + deserializedChatCompletions.systemFingerprint = systemFingerprint; + return deserializedChatCompletions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolCall.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolCall.java index 92db0866b4095..d7b6d23ee00f4 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolCall.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolCall.java @@ -5,21 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A tool call to a function tool, issued by the model in evaluation of a configured function tool, that represents * a function invocation needed for a subsequent chat completions request to resolve. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatCompletionsFunctionToolCall.class, - visible = true) -@JsonTypeName("function") @Immutable public final class ChatCompletionsFunctionToolCall extends ChatCompletionsToolCall { @@ -27,7 +21,6 @@ public final class ChatCompletionsFunctionToolCall extends ChatCompletionsToolCa * The details of the function invocation requested by the tool call. */ @Generated - @JsonProperty(value = "function") private final FunctionCall function; /** @@ -36,10 +29,9 @@ public final class ChatCompletionsFunctionToolCall extends ChatCompletionsToolCa * @param id the id value to set. * @param function the function value to set. */ - @JsonCreator - public ChatCompletionsFunctionToolCall(@JsonProperty(value = "id") String id, - @JsonProperty(value = "function") FunctionCall function) { - super(id, "function"); + @Generated + public ChatCompletionsFunctionToolCall(String id, FunctionCall function) { + super(id); this.function = function; } @@ -52,4 +44,69 @@ public ChatCompletionsFunctionToolCall(@JsonProperty(value = "id") String id, public FunctionCall getFunction() { return this.function; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", getId()); + jsonWriter.writeJsonField("function", this.function); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsFunctionToolCall from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsFunctionToolCall 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 ChatCompletionsFunctionToolCall. + */ + @Generated + public static ChatCompletionsFunctionToolCall fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + FunctionCall function = null; + String type = "function"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("function".equals(fieldName)) { + function = FunctionCall.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatCompletionsFunctionToolCall deserializedChatCompletionsFunctionToolCall + = new ChatCompletionsFunctionToolCall(id, function); + deserializedChatCompletionsFunctionToolCall.type = type; + return deserializedChatCompletionsFunctionToolCall; + }); + } + + /* + * The object type. + */ + @Generated + private String type = "function"; + + /** + * Get the type property: The object type. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolDefinition.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolDefinition.java index 0a604e5cda647..e601c35e3d839 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolDefinition.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolDefinition.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The definition information for a chat completions function tool that can call a function in response to a tool call. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatCompletionsFunctionToolDefinition.class, - visible = true) -@JsonTypeName("function") @Immutable public final class ChatCompletionsFunctionToolDefinition extends ChatCompletionsToolDefinition { @@ -27,7 +20,6 @@ public final class ChatCompletionsFunctionToolDefinition extends ChatCompletions * The function definition details for the function tool. */ @Generated - @JsonProperty(value = "function") private final FunctionDefinition function; /** @@ -36,8 +28,7 @@ public final class ChatCompletionsFunctionToolDefinition extends ChatCompletions * @param function the function value to set. */ @Generated - @JsonCreator - public ChatCompletionsFunctionToolDefinition(@JsonProperty(value = "function") FunctionDefinition function) { + public ChatCompletionsFunctionToolDefinition(FunctionDefinition function) { this.function = function; } @@ -55,8 +46,6 @@ public FunctionDefinition getFunction() { * The object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type = "function"; /** @@ -69,4 +58,48 @@ public FunctionDefinition getFunction() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("function", this.function); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsFunctionToolDefinition from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsFunctionToolDefinition 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 ChatCompletionsFunctionToolDefinition. + */ + @Generated + public static ChatCompletionsFunctionToolDefinition fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FunctionDefinition function = null; + String type = "function"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("function".equals(fieldName)) { + function = FunctionDefinition.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatCompletionsFunctionToolDefinition deserializedChatCompletionsFunctionToolDefinition + = new ChatCompletionsFunctionToolDefinition(function); + deserializedChatCompletionsFunctionToolDefinition.type = type; + return deserializedChatCompletionsFunctionToolDefinition; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolSelection.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolSelection.java index 239e3635f8be3..fb873463feb4d 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolSelection.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsFunctionToolSelection.java @@ -5,20 +5,23 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A tool selection of a specific, named function tool that will limit chat completions to using the named function. */ @Immutable -public final class ChatCompletionsFunctionToolSelection { +public final class ChatCompletionsFunctionToolSelection + implements JsonSerializable { /* * The name of the function that should be called. */ @Generated - @JsonProperty(value = "name") private final String name; /** @@ -27,8 +30,7 @@ public final class ChatCompletionsFunctionToolSelection { * @param name the name value to set. */ @Generated - @JsonCreator - public ChatCompletionsFunctionToolSelection(@JsonProperty(value = "name") String name) { + public ChatCompletionsFunctionToolSelection(String name) { this.name = name; } @@ -41,4 +43,41 @@ public ChatCompletionsFunctionToolSelection(@JsonProperty(value = "name") String public String getName() { return this.name; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsFunctionToolSelection from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsFunctionToolSelection 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 ChatCompletionsFunctionToolSelection. + */ + @Generated + public static ChatCompletionsFunctionToolSelection fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + name = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ChatCompletionsFunctionToolSelection(name); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsJsonResponseFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsJsonResponseFormat.java index 72e293e833926..237fc2c807090 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsJsonResponseFormat.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsJsonResponseFormat.java @@ -5,20 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A response format for Chat Completions that restricts responses to emitting valid JSON objects. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatCompletionsJsonResponseFormat.class, - visible = true) -@JsonTypeName("json_object") @Immutable public final class ChatCompletionsJsonResponseFormat extends ChatCompletionsResponseFormat { @@ -33,8 +27,6 @@ public ChatCompletionsJsonResponseFormat() { * The discriminated type for the response format. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type = "json_object"; /** @@ -47,4 +39,41 @@ public ChatCompletionsJsonResponseFormat() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsJsonResponseFormat from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsJsonResponseFormat if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ChatCompletionsJsonResponseFormat. + */ + @Generated + public static ChatCompletionsJsonResponseFormat fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionsJsonResponseFormat deserializedChatCompletionsJsonResponseFormat + = new ChatCompletionsJsonResponseFormat(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedChatCompletionsJsonResponseFormat.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedChatCompletionsJsonResponseFormat; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsNamedFunctionToolSelection.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsNamedFunctionToolSelection.java index 2487c662fb584..95f229e1c72b2 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsNamedFunctionToolSelection.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsNamedFunctionToolSelection.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A tool selection of a specific, named function tool that will limit chat completions to using the named function. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatCompletionsNamedFunctionToolSelection.class, - visible = true) -@JsonTypeName("function") @Immutable public final class ChatCompletionsNamedFunctionToolSelection extends ChatCompletionsNamedToolSelection { @@ -27,7 +20,6 @@ public final class ChatCompletionsNamedFunctionToolSelection extends ChatComplet * The function that should be called. */ @Generated - @JsonProperty(value = "function") private final ChatCompletionsFunctionToolSelection function; /** @@ -36,9 +28,7 @@ public final class ChatCompletionsNamedFunctionToolSelection extends ChatComplet * @param function the function value to set. */ @Generated - @JsonCreator - public ChatCompletionsNamedFunctionToolSelection( - @JsonProperty(value = "function") ChatCompletionsFunctionToolSelection function) { + public ChatCompletionsNamedFunctionToolSelection(ChatCompletionsFunctionToolSelection function) { this.function = function; } @@ -56,8 +46,6 @@ public ChatCompletionsFunctionToolSelection getFunction() { * The object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type = "function"; /** @@ -70,4 +58,48 @@ public ChatCompletionsFunctionToolSelection getFunction() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("function", this.function); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsNamedFunctionToolSelection from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsNamedFunctionToolSelection 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 ChatCompletionsNamedFunctionToolSelection. + */ + @Generated + public static ChatCompletionsNamedFunctionToolSelection fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionsFunctionToolSelection function = null; + String type = "function"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("function".equals(fieldName)) { + function = ChatCompletionsFunctionToolSelection.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatCompletionsNamedFunctionToolSelection deserializedChatCompletionsNamedFunctionToolSelection + = new ChatCompletionsNamedFunctionToolSelection(function); + deserializedChatCompletionsNamedFunctionToolSelection.type = type; + return deserializedChatCompletionsNamedFunctionToolSelection; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsNamedToolSelection.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsNamedToolSelection.java index ff87487344a4b..427f8a167db72 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsNamedToolSelection.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsNamedToolSelection.java @@ -5,24 +5,17 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * An abstract representation of an explicit, named tool selection to use for a chat completions request. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatCompletionsNamedToolSelection.class, - visible = true) -@JsonTypeName("ChatCompletionsNamedToolSelection") -@JsonSubTypes({ @JsonSubTypes.Type(name = "function", value = ChatCompletionsNamedFunctionToolSelection.class) }) @Immutable -public class ChatCompletionsNamedToolSelection { +public class ChatCompletionsNamedToolSelection implements JsonSerializable { /** * Creates an instance of ChatCompletionsNamedToolSelection class. @@ -36,8 +29,6 @@ public ChatCompletionsNamedToolSelection() { * The object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type; /** @@ -49,4 +40,68 @@ public ChatCompletionsNamedToolSelection() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsNamedToolSelection from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsNamedToolSelection if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ChatCompletionsNamedToolSelection. + */ + @Generated + public static ChatCompletionsNamedToolSelection fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("function".equals(discriminatorValue)) { + return ChatCompletionsNamedFunctionToolSelection.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static ChatCompletionsNamedToolSelection fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionsNamedToolSelection deserializedChatCompletionsNamedToolSelection + = new ChatCompletionsNamedToolSelection(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedChatCompletionsNamedToolSelection.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedChatCompletionsNamedToolSelection; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsOptions.java index 4d5665a1bde2b..cc43eb9e54707 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsOptions.java @@ -6,12 +6,13 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; import com.azure.core.util.BinaryData; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; import java.util.Map; -import com.azure.ai.openai.implementation.models.FunctionCallPreset; -import com.fasterxml.jackson.annotation.JsonIgnore; /** * The configuration information for a chat completions request. @@ -19,7 +20,7 @@ * provided prompt data. */ @Fluent -public final class ChatCompletionsOptions { +public final class ChatCompletionsOptions implements JsonSerializable { /* * The collection of context messages associated with this chat completions request. @@ -28,14 +29,12 @@ public final class ChatCompletionsOptions { * Assistant roles. */ @Generated - @JsonProperty(value = "messages") private final List messages; /* * The maximum number of tokens to generate. */ @Generated - @JsonProperty(value = "max_tokens") private Integer maxTokens; /* @@ -46,7 +45,6 @@ public final class ChatCompletionsOptions { * interaction of these two settings is difficult to predict. */ @Generated - @JsonProperty(value = "temperature") private Double temperature; /* @@ -58,7 +56,6 @@ public final class ChatCompletionsOptions { * interaction of these two settings is difficult to predict. */ @Generated - @JsonProperty(value = "top_p") private Double topP; /* @@ -69,7 +66,6 @@ public final class ChatCompletionsOptions { * score varies by model. */ @Generated - @JsonProperty(value = "logit_bias") private Map logitBias; /* @@ -77,7 +73,6 @@ public final class ChatCompletionsOptions { * or rate-limiting purposes. */ @Generated - @JsonProperty(value = "user") private String user; /* @@ -87,14 +82,12 @@ public final class ChatCompletionsOptions { * Use carefully and ensure reasonable settings for max_tokens and stop. */ @Generated - @JsonProperty(value = "n") private Integer n; /* * A collection of textual sequences that will end completions generation. */ @Generated - @JsonProperty(value = "stop") private List stop; /* @@ -104,7 +97,6 @@ public final class ChatCompletionsOptions { * model's likelihood to output new topics. */ @Generated - @JsonProperty(value = "presence_penalty") private Double presencePenalty; /* @@ -114,14 +106,12 @@ public final class ChatCompletionsOptions { * decrease the likelihood of the model repeating the same statements verbatim. */ @Generated - @JsonProperty(value = "frequency_penalty") private Double frequencyPenalty; /* * A value indicating whether chat completions should be streamed for this request. */ @Generated - @JsonProperty(value = "stream") private Boolean stream; /* @@ -130,7 +120,6 @@ public final class ChatCompletionsOptions { * resource URI that's connected to. */ @Generated - @JsonProperty(value = "model") private String model; /** @@ -139,8 +128,7 @@ public final class ChatCompletionsOptions { * @param messages the messages value to set. */ @Generated - @JsonCreator - public ChatCompletionsOptions(@JsonProperty(value = "messages") List messages) { + public ChatCompletionsOptions(List messages) { this.messages = messages; } @@ -461,7 +449,6 @@ public ChatCompletionsOptions setModel(String model) { * A list of functions the model may generate JSON inputs for. */ @Generated - @JsonProperty(value = "functions") private List functions; /* @@ -471,13 +458,11 @@ public ChatCompletionsOptions setModel(String model) { * "none" is the default when no functions are present. "auto" is the default if functions are present. */ @Generated - @JsonProperty(value = "function_call") private BinaryData functionCall; /* * Field not used for serialization. This is a convenience helper field for the serialization of "function_call". */ - @JsonIgnore private FunctionCallConfig functionCallConfig; /** @@ -551,13 +536,7 @@ public FunctionCallConfig getFunctionCall() { */ public ChatCompletionsOptions setFunctionCall(FunctionCallConfig functionCallConfig) { this.functionCallConfig = functionCallConfig; - if (FunctionCallPreset.values() - .stream() - .anyMatch(preset -> preset.toString().equals(functionCallConfig.getName()))) { - this.functionCall = BinaryData.fromObject(FunctionCallPreset.fromString(this.functionCallConfig.getName())); - } else { - this.functionCall = BinaryData.fromObject(new FunctionName(this.functionCallConfig.getName())); - } + this.functionCall = BinaryData.fromObject(new FunctionName(this.functionCallConfig.getName())); return this; } @@ -566,7 +545,6 @@ public ChatCompletionsOptions setFunctionCall(FunctionCallConfig functionCallCon * This additional specification is only compatible with Azure OpenAI. */ @Generated - @JsonProperty(value = "data_sources") private List dataSources; /** @@ -597,7 +575,6 @@ public ChatCompletionsOptions setDataSources(List tools; /* * If specified, the model will configure which of the provided tools it can use for the chat completions response. */ @Generated - @JsonProperty(value = "tool_choice") private BinaryData toolChoice; /** @@ -760,14 +733,12 @@ public ChatCompletionsOptions setToolChoice(BinaryData toolChoice) { * Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. This option is currently not available on the `gpt-4-vision-preview` model. */ @Generated - @JsonProperty(value = "logprobs") private Boolean logprobs; /* * An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. */ @Generated - @JsonProperty(value = "top_logprobs") private Integer topLogprobs; /** @@ -821,4 +792,152 @@ public ChatCompletionsOptions setTopLogprobs(Integer topLogprobs) { this.topLogprobs = topLogprobs; return this; } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("messages", this.messages, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("functions", this.functions, (writer, element) -> writer.writeJson(element)); + if (this.functionCall != null) { + jsonWriter.writeRawField("function_call", this.functionCall.toString()); + } + jsonWriter.writeNumberField("max_tokens", this.maxTokens); + jsonWriter.writeNumberField("temperature", this.temperature); + jsonWriter.writeNumberField("top_p", this.topP); + jsonWriter.writeMapField("logit_bias", this.logitBias, (writer, element) -> writer.writeInt(element)); + jsonWriter.writeStringField("user", this.user); + jsonWriter.writeNumberField("n", this.n); + jsonWriter.writeArrayField("stop", this.stop, (writer, element) -> writer.writeString(element)); + jsonWriter.writeNumberField("presence_penalty", this.presencePenalty); + jsonWriter.writeNumberField("frequency_penalty", this.frequencyPenalty); + jsonWriter.writeBooleanField("stream", this.stream); + jsonWriter.writeStringField("model", this.model); + jsonWriter.writeArrayField("data_sources", this.dataSources, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("enhancements", this.enhancements); + jsonWriter.writeNumberField("seed", this.seed); + jsonWriter.writeBooleanField("logprobs", this.logprobs); + jsonWriter.writeNumberField("top_logprobs", this.topLogprobs); + jsonWriter.writeJsonField("response_format", this.responseFormat); + jsonWriter.writeArrayField("tools", this.tools, (writer, element) -> writer.writeJson(element)); + if (this.toolChoice != null) { + jsonWriter.writeRawField("tool_choice", this.toolChoice.toString()); + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsOptions 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 ChatCompletionsOptions. + */ + @Generated + public static ChatCompletionsOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List messages = null; + List functions = null; + BinaryData functionCall = null; + Integer maxTokens = null; + Double temperature = null; + Double topP = null; + Map logitBias = null; + String user = null; + Integer n = null; + List stop = null; + Double presencePenalty = null; + Double frequencyPenalty = null; + Boolean stream = null; + String model = null; + List dataSources = null; + AzureChatEnhancementConfiguration enhancements = null; + Long seed = null; + Boolean logprobs = null; + Integer topLogprobs = null; + ChatCompletionsResponseFormat responseFormat = null; + List tools = null; + BinaryData toolChoice = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("messages".equals(fieldName)) { + messages = reader.readArray(reader1 -> ChatRequestMessage.fromJson(reader1)); + } else if ("functions".equals(fieldName)) { + functions = reader.readArray(reader1 -> FunctionDefinition.fromJson(reader1)); + } else if ("function_call".equals(fieldName)) { + functionCall + = reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())); + } else if ("max_tokens".equals(fieldName)) { + maxTokens = reader.getNullable(JsonReader::getInt); + } else if ("temperature".equals(fieldName)) { + temperature = reader.getNullable(JsonReader::getDouble); + } else if ("top_p".equals(fieldName)) { + topP = reader.getNullable(JsonReader::getDouble); + } else if ("logit_bias".equals(fieldName)) { + logitBias = reader.readMap(reader1 -> reader1.getInt()); + } else if ("user".equals(fieldName)) { + user = reader.getString(); + } else if ("n".equals(fieldName)) { + n = reader.getNullable(JsonReader::getInt); + } else if ("stop".equals(fieldName)) { + stop = reader.readArray(reader1 -> reader1.getString()); + } else if ("presence_penalty".equals(fieldName)) { + presencePenalty = reader.getNullable(JsonReader::getDouble); + } else if ("frequency_penalty".equals(fieldName)) { + frequencyPenalty = reader.getNullable(JsonReader::getDouble); + } else if ("stream".equals(fieldName)) { + stream = reader.getNullable(JsonReader::getBoolean); + } else if ("model".equals(fieldName)) { + model = reader.getString(); + } else if ("data_sources".equals(fieldName)) { + dataSources = reader.readArray(reader1 -> AzureChatExtensionConfiguration.fromJson(reader1)); + } else if ("enhancements".equals(fieldName)) { + enhancements = AzureChatEnhancementConfiguration.fromJson(reader); + } else if ("seed".equals(fieldName)) { + seed = reader.getNullable(JsonReader::getLong); + } else if ("logprobs".equals(fieldName)) { + logprobs = reader.getNullable(JsonReader::getBoolean); + } else if ("top_logprobs".equals(fieldName)) { + topLogprobs = reader.getNullable(JsonReader::getInt); + } else if ("response_format".equals(fieldName)) { + responseFormat = ChatCompletionsResponseFormat.fromJson(reader); + } else if ("tools".equals(fieldName)) { + tools = reader.readArray(reader1 -> ChatCompletionsToolDefinition.fromJson(reader1)); + } else if ("tool_choice".equals(fieldName)) { + toolChoice + = reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())); + } else { + reader.skipChildren(); + } + } + ChatCompletionsOptions deserializedChatCompletionsOptions = new ChatCompletionsOptions(messages); + deserializedChatCompletionsOptions.functions = functions; + deserializedChatCompletionsOptions.functionCall = functionCall; + deserializedChatCompletionsOptions.maxTokens = maxTokens; + deserializedChatCompletionsOptions.temperature = temperature; + deserializedChatCompletionsOptions.topP = topP; + deserializedChatCompletionsOptions.logitBias = logitBias; + deserializedChatCompletionsOptions.user = user; + deserializedChatCompletionsOptions.n = n; + deserializedChatCompletionsOptions.stop = stop; + deserializedChatCompletionsOptions.presencePenalty = presencePenalty; + deserializedChatCompletionsOptions.frequencyPenalty = frequencyPenalty; + deserializedChatCompletionsOptions.stream = stream; + deserializedChatCompletionsOptions.model = model; + deserializedChatCompletionsOptions.dataSources = dataSources; + deserializedChatCompletionsOptions.enhancements = enhancements; + deserializedChatCompletionsOptions.seed = seed; + deserializedChatCompletionsOptions.logprobs = logprobs; + deserializedChatCompletionsOptions.topLogprobs = topLogprobs; + deserializedChatCompletionsOptions.responseFormat = responseFormat; + deserializedChatCompletionsOptions.tools = tools; + deserializedChatCompletionsOptions.toolChoice = toolChoice; + return deserializedChatCompletionsOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsResponseFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsResponseFormat.java index c09cf008c7c52..2126c30fce20a 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsResponseFormat.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsResponseFormat.java @@ -5,27 +5,18 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON * mode. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatCompletionsResponseFormat.class, - visible = true) -@JsonTypeName("ChatCompletionsResponseFormat") -@JsonSubTypes({ - @JsonSubTypes.Type(name = "text", value = ChatCompletionsTextResponseFormat.class), - @JsonSubTypes.Type(name = "json_object", value = ChatCompletionsJsonResponseFormat.class) }) @Immutable -public class ChatCompletionsResponseFormat { +public class ChatCompletionsResponseFormat implements JsonSerializable { /** * Creates an instance of ChatCompletionsResponseFormat class. @@ -39,8 +30,6 @@ public ChatCompletionsResponseFormat() { * The discriminated type for the response format. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type; /** @@ -52,4 +41,70 @@ public ChatCompletionsResponseFormat() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsResponseFormat from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsResponseFormat if the JsonReader was pointing to an instance of it, or null + * if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ChatCompletionsResponseFormat. + */ + @Generated + public static ChatCompletionsResponseFormat fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("text".equals(discriminatorValue)) { + return ChatCompletionsTextResponseFormat.fromJson(readerToUse.reset()); + } else if ("json_object".equals(discriminatorValue)) { + return ChatCompletionsJsonResponseFormat.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static ChatCompletionsResponseFormat fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionsResponseFormat deserializedChatCompletionsResponseFormat + = new ChatCompletionsResponseFormat(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedChatCompletionsResponseFormat.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedChatCompletionsResponseFormat; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsTextResponseFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsTextResponseFormat.java index 72a5e43f09bfd..f81541992ceef 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsTextResponseFormat.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsTextResponseFormat.java @@ -5,21 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response * content that adheres to a specific schema. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatCompletionsTextResponseFormat.class, - visible = true) -@JsonTypeName("text") @Immutable public final class ChatCompletionsTextResponseFormat extends ChatCompletionsResponseFormat { @@ -34,8 +28,6 @@ public ChatCompletionsTextResponseFormat() { * The discriminated type for the response format. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type = "text"; /** @@ -48,4 +40,41 @@ public ChatCompletionsTextResponseFormat() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsTextResponseFormat from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsTextResponseFormat if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ChatCompletionsTextResponseFormat. + */ + @Generated + public static ChatCompletionsTextResponseFormat fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionsTextResponseFormat deserializedChatCompletionsTextResponseFormat + = new ChatCompletionsTextResponseFormat(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedChatCompletionsTextResponseFormat.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedChatCompletionsTextResponseFormat; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolCall.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolCall.java index b31af6fc26840..66d559f86d759 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolCall.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolCall.java @@ -5,31 +5,29 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonGetter; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested * chat completion. */ -@JsonTypeName("ChatCompletionsToolCall") -@JsonSubTypes({ @JsonSubTypes.Type(name = "function", value = ChatCompletionsFunctionToolCall.class) }) @Immutable -@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, defaultImpl = ChatCompletionsToolCall.class) -public class ChatCompletionsToolCall { +public class ChatCompletionsToolCall implements JsonSerializable { /* * The ID of the tool call. */ @Generated - @JsonProperty(value = "id") private final String id; - @JsonProperty("type") + /* + * The object type. + */ + @Generated private String type; /** @@ -43,25 +41,95 @@ public String getId() { } /** - * Get the type property: The type pf the tool call. + * Get the type property: The object type. * * @return the type value. */ - @JsonGetter + @Generated public String getType() { return this.type; } + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsToolCall from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsToolCall 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 ChatCompletionsToolCall. + */ + public static ChatCompletionsToolCall fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else if ("function".equals(fieldName)) { + discriminatorValue = "function"; + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("function".equals(discriminatorValue)) { + return ChatCompletionsFunctionToolCall.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static ChatCompletionsToolCall fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String type = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatCompletionsToolCall deserializedChatCompletionsToolCall = new ChatCompletionsToolCall(id); + deserializedChatCompletionsToolCall.type = type; + return deserializedChatCompletionsToolCall; + }); + } + /** * Creates an instance of ChatCompletionsToolCall class. * * @param id the id value to set. - * @param type the type value to set. */ @Generated - @JsonCreator - public ChatCompletionsToolCall(@JsonProperty(value = "id") String id, @JsonProperty(value = "type") String type) { + public ChatCompletionsToolCall(String id) { + this.type = "ChatCompletionsToolCall"; this.id = id; - this.type = type; } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolDefinition.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolDefinition.java index 6b378e568dade..17f2e88104f3a 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolDefinition.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolDefinition.java @@ -5,24 +5,17 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * An abstract representation of a tool that can be used by the model to improve a chat completions response. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatCompletionsToolDefinition.class, - visible = true) -@JsonTypeName("ChatCompletionsToolDefinition") -@JsonSubTypes({ @JsonSubTypes.Type(name = "function", value = ChatCompletionsFunctionToolDefinition.class) }) @Immutable -public class ChatCompletionsToolDefinition { +public class ChatCompletionsToolDefinition implements JsonSerializable { /** * Creates an instance of ChatCompletionsToolDefinition class. @@ -36,8 +29,6 @@ public ChatCompletionsToolDefinition() { * The object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type; /** @@ -49,4 +40,68 @@ public ChatCompletionsToolDefinition() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsToolDefinition from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsToolDefinition if the JsonReader was pointing to an instance of it, or null + * if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ChatCompletionsToolDefinition. + */ + @Generated + public static ChatCompletionsToolDefinition fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("function".equals(discriminatorValue)) { + return ChatCompletionsFunctionToolDefinition.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static ChatCompletionsToolDefinition fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionsToolDefinition deserializedChatCompletionsToolDefinition + = new ChatCompletionsToolDefinition(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedChatCompletionsToolDefinition.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedChatCompletionsToolDefinition; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolSelectionPreset.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolSelectionPreset.java index 5c621bc6ab374..81e4bd81eab7a 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolSelectionPreset.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionsToolSelectionPreset.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -44,7 +43,6 @@ public ChatCompletionsToolSelectionPreset() { * @return the corresponding ChatCompletionsToolSelectionPreset. */ @Generated - @JsonCreator public static ChatCompletionsToolSelectionPreset fromString(String name) { return fromString(name, ChatCompletionsToolSelectionPreset.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatFinishDetails.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatFinishDetails.java index e8372118668a6..b1574cf83b3bd 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatFinishDetails.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatFinishDetails.java @@ -5,22 +5,17 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * An abstract representation of structured information about why a chat completions response terminated. */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = ChatFinishDetails.class, visible = true) -@JsonTypeName("ChatFinishDetails") -@JsonSubTypes({ - @JsonSubTypes.Type(name = "stop", value = StopFinishDetails.class), - @JsonSubTypes.Type(name = "max_tokens", value = MaxTokensFinishDetails.class) }) @Immutable -public class ChatFinishDetails { +public class ChatFinishDetails implements JsonSerializable { /** * Creates an instance of ChatFinishDetails class. @@ -34,8 +29,6 @@ protected ChatFinishDetails() { * The object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type; /** @@ -47,4 +40,69 @@ protected ChatFinishDetails() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatFinishDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatFinishDetails if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the ChatFinishDetails. + */ + @Generated + public static ChatFinishDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("stop".equals(discriminatorValue)) { + return StopFinishDetails.fromJson(readerToUse.reset()); + } else if ("max_tokens".equals(discriminatorValue)) { + return MaxTokensFinishDetails.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static ChatFinishDetails fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatFinishDetails deserializedChatFinishDetails = new ChatFinishDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedChatFinishDetails.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedChatFinishDetails; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageContentItem.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageContentItem.java index c10532cfdb5ca..cfdd4128c8552 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageContentItem.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageContentItem.java @@ -5,22 +5,17 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * An abstract representation of a structured content item within a chat message. */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = ChatMessageContentItem.class, visible = true) -@JsonTypeName("ChatMessageContentItem") -@JsonSubTypes({ - @JsonSubTypes.Type(name = "text", value = ChatMessageTextContentItem.class), - @JsonSubTypes.Type(name = "image_url", value = ChatMessageImageContentItem.class) }) @Immutable -public class ChatMessageContentItem { +public class ChatMessageContentItem implements JsonSerializable { /** * Creates an instance of ChatMessageContentItem class. @@ -34,8 +29,6 @@ public ChatMessageContentItem() { * The discriminated object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type; /** @@ -47,4 +40,69 @@ public ChatMessageContentItem() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatMessageContentItem from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatMessageContentItem if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IOException If an error occurs while reading the ChatMessageContentItem. + */ + @Generated + public static ChatMessageContentItem fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("text".equals(discriminatorValue)) { + return ChatMessageTextContentItem.fromJson(readerToUse.reset()); + } else if ("image_url".equals(discriminatorValue)) { + return ChatMessageImageContentItem.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static ChatMessageContentItem fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatMessageContentItem deserializedChatMessageContentItem = new ChatMessageContentItem(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedChatMessageContentItem.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedChatMessageContentItem; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageContentItem.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageContentItem.java index bde3f2585e4df..e8186a7829584 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageContentItem.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageContentItem.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A structured chat content item containing an image reference. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatMessageImageContentItem.class, - visible = true) -@JsonTypeName("image_url") @Immutable public final class ChatMessageImageContentItem extends ChatMessageContentItem { @@ -27,7 +20,6 @@ public final class ChatMessageImageContentItem extends ChatMessageContentItem { * An internet location, which must be accessible to the model,from which the image may be retrieved. */ @Generated - @JsonProperty(value = "image_url") private final ChatMessageImageUrl imageUrl; /** @@ -36,8 +28,7 @@ public final class ChatMessageImageContentItem extends ChatMessageContentItem { * @param imageUrl the imageUrl value to set. */ @Generated - @JsonCreator - public ChatMessageImageContentItem(@JsonProperty(value = "image_url") ChatMessageImageUrl imageUrl) { + public ChatMessageImageContentItem(ChatMessageImageUrl imageUrl) { this.imageUrl = imageUrl; } @@ -56,8 +47,6 @@ public ChatMessageImageUrl getImageUrl() { * The discriminated object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type = "image_url"; /** @@ -70,4 +59,48 @@ public ChatMessageImageUrl getImageUrl() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("image_url", this.imageUrl); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatMessageImageContentItem from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatMessageImageContentItem 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 ChatMessageImageContentItem. + */ + @Generated + public static ChatMessageImageContentItem fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatMessageImageUrl imageUrl = null; + String type = "image_url"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("image_url".equals(fieldName)) { + imageUrl = ChatMessageImageUrl.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatMessageImageContentItem deserializedChatMessageImageContentItem + = new ChatMessageImageContentItem(imageUrl); + deserializedChatMessageImageContentItem.type = type; + return deserializedChatMessageImageContentItem; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageDetailLevel.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageDetailLevel.java index e64a4dbcea02f..3da54dc6d29ba 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageDetailLevel.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageDetailLevel.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -50,7 +49,6 @@ public ChatMessageImageDetailLevel() { * @return the corresponding ChatMessageImageDetailLevel. */ @Generated - @JsonCreator public static ChatMessageImageDetailLevel fromString(String name) { return fromString(name, ChatMessageImageDetailLevel.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageUrl.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageUrl.java index a66a1a64492dd..3dedd61fce2a5 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageUrl.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageImageUrl.java @@ -5,20 +5,22 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * An internet location from which the model may retrieve an image. */ @Fluent -public final class ChatMessageImageUrl { +public final class ChatMessageImageUrl implements JsonSerializable { /* * The URL of the image. */ @Generated - @JsonProperty(value = "url") private final String url; /** @@ -27,8 +29,7 @@ public final class ChatMessageImageUrl { * @param url the url value to set. */ @Generated - @JsonCreator - public ChatMessageImageUrl(@JsonProperty(value = "url") String url) { + public ChatMessageImageUrl(String url) { this.url = url; } @@ -47,7 +48,6 @@ public String getUrl() { * accuracy. */ @Generated - @JsonProperty(value = "detail") private ChatMessageImageDetailLevel detail; /** @@ -75,4 +75,47 @@ public ChatMessageImageUrl setDetail(ChatMessageImageDetailLevel detail) { this.detail = detail; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("detail", this.detail == null ? null : this.detail.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatMessageImageUrl from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatMessageImageUrl 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 ChatMessageImageUrl. + */ + @Generated + public static ChatMessageImageUrl fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String url = null; + ChatMessageImageDetailLevel detail = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("url".equals(fieldName)) { + url = reader.getString(); + } else if ("detail".equals(fieldName)) { + detail = ChatMessageImageDetailLevel.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + ChatMessageImageUrl deserializedChatMessageImageUrl = new ChatMessageImageUrl(url); + deserializedChatMessageImageUrl.detail = detail; + return deserializedChatMessageImageUrl; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageTextContentItem.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageTextContentItem.java index e7f0b95659e92..2582eeef70108 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageTextContentItem.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageTextContentItem.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A structured chat content item containing plain text. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ChatMessageTextContentItem.class, - visible = true) -@JsonTypeName("text") @Immutable public final class ChatMessageTextContentItem extends ChatMessageContentItem { @@ -27,7 +20,6 @@ public final class ChatMessageTextContentItem extends ChatMessageContentItem { * The content of the message. */ @Generated - @JsonProperty(value = "text") private final String text; /** @@ -36,8 +28,7 @@ public final class ChatMessageTextContentItem extends ChatMessageContentItem { * @param text the text value to set. */ @Generated - @JsonCreator - public ChatMessageTextContentItem(@JsonProperty(value = "text") String text) { + public ChatMessageTextContentItem(String text) { this.text = text; } @@ -55,8 +46,6 @@ public String getText() { * The discriminated object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type = "text"; /** @@ -69,4 +58,47 @@ public String getText() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatMessageTextContentItem from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatMessageTextContentItem 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 ChatMessageTextContentItem. + */ + @Generated + public static ChatMessageTextContentItem fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String text = null; + String type = "text"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("text".equals(fieldName)) { + text = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatMessageTextContentItem deserializedChatMessageTextContentItem = new ChatMessageTextContentItem(text); + deserializedChatMessageTextContentItem.type = type; + return deserializedChatMessageTextContentItem; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestAssistantMessage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestAssistantMessage.java index 24b01d00852ba..0f8b3865a3aef 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestAssistantMessage.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestAssistantMessage.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * A request chat message representing response or action from the assistant. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "role", - defaultImpl = ChatRequestAssistantMessage.class, - visible = true) -@JsonTypeName("assistant") @Fluent public final class ChatRequestAssistantMessage extends ChatRequestMessage { @@ -28,14 +21,12 @@ public final class ChatRequestAssistantMessage extends ChatRequestMessage { * The content of the message. */ @Generated - @JsonProperty(value = "content") private final String content; /* * An optional name for the participant. */ @Generated - @JsonProperty(value = "name") private String name; /* @@ -43,7 +34,6 @@ public final class ChatRequestAssistantMessage extends ChatRequestMessage { * completions request to resolve as configured. */ @Generated - @JsonProperty(value = "tool_calls") private List toolCalls; /* @@ -51,7 +41,6 @@ public final class ChatRequestAssistantMessage extends ChatRequestMessage { * completions request to resolve as configured. */ @Generated - @JsonProperty(value = "function_call") private FunctionCall functionCall; /** @@ -60,8 +49,7 @@ public final class ChatRequestAssistantMessage extends ChatRequestMessage { * @param content the content value to set. */ @Generated - @JsonCreator - public ChatRequestAssistantMessage(@JsonProperty(value = "content") String content) { + public ChatRequestAssistantMessage(String content) { this.content = content; } @@ -153,8 +141,6 @@ public ChatRequestAssistantMessage setFunctionCall(FunctionCall functionCall) { * The chat role associated with this message. */ @Generated - @JsonTypeId - @JsonProperty(value = "role") private ChatRole role = ChatRole.ASSISTANT; /** @@ -167,4 +153,63 @@ public ChatRequestAssistantMessage setFunctionCall(FunctionCall functionCall) { public ChatRole getRole() { return this.role; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("content", this.content); + jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeArrayField("tool_calls", this.toolCalls, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("function_call", this.functionCall); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatRequestAssistantMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatRequestAssistantMessage 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 ChatRequestAssistantMessage. + */ + @Generated + public static ChatRequestAssistantMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String content = null; + ChatRole role = ChatRole.ASSISTANT; + String name = null; + List toolCalls = null; + FunctionCall functionCall = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("content".equals(fieldName)) { + content = reader.getString(); + } else if ("role".equals(fieldName)) { + role = ChatRole.fromString(reader.getString()); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("tool_calls".equals(fieldName)) { + toolCalls = reader.readArray(reader1 -> ChatCompletionsToolCall.fromJson(reader1)); + } else if ("function_call".equals(fieldName)) { + functionCall = FunctionCall.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ChatRequestAssistantMessage deserializedChatRequestAssistantMessage + = new ChatRequestAssistantMessage(content); + deserializedChatRequestAssistantMessage.role = role; + deserializedChatRequestAssistantMessage.name = name; + deserializedChatRequestAssistantMessage.toolCalls = toolCalls; + deserializedChatRequestAssistantMessage.functionCall = functionCall; + return deserializedChatRequestAssistantMessage; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestFunctionMessage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestFunctionMessage.java index 4bca4ca06db9a..f4b11585af856 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestFunctionMessage.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestFunctionMessage.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A request chat message representing requested output from a configured function. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "role", - defaultImpl = ChatRequestFunctionMessage.class, - visible = true) -@JsonTypeName("function") @Immutable public final class ChatRequestFunctionMessage extends ChatRequestMessage { @@ -27,14 +20,12 @@ public final class ChatRequestFunctionMessage extends ChatRequestMessage { * The name of the function that was called to produce output. */ @Generated - @JsonProperty(value = "name") private final String name; /* * The output of the function as requested by the function call. */ @Generated - @JsonProperty(value = "content") private final String content; /** @@ -44,9 +35,7 @@ public final class ChatRequestFunctionMessage extends ChatRequestMessage { * @param content the content value to set. */ @Generated - @JsonCreator - public ChatRequestFunctionMessage(@JsonProperty(value = "name") String name, - @JsonProperty(value = "content") String content) { + public ChatRequestFunctionMessage(String name, String content) { this.name = name; this.content = content; } @@ -75,8 +64,6 @@ public String getContent() { * The chat role associated with this message. */ @Generated - @JsonTypeId - @JsonProperty(value = "role") private ChatRole role = ChatRole.FUNCTION; /** @@ -89,4 +76,52 @@ public String getContent() { public ChatRole getRole() { return this.role; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("content", this.content); + jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatRequestFunctionMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatRequestFunctionMessage 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 ChatRequestFunctionMessage. + */ + @Generated + public static ChatRequestFunctionMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + String content = null; + ChatRole role = ChatRole.FUNCTION; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("content".equals(fieldName)) { + content = reader.getString(); + } else if ("role".equals(fieldName)) { + role = ChatRole.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + ChatRequestFunctionMessage deserializedChatRequestFunctionMessage + = new ChatRequestFunctionMessage(name, content); + deserializedChatRequestFunctionMessage.role = role; + return deserializedChatRequestFunctionMessage; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestMessage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestMessage.java index ba8deafc4d68c..20788383ab727 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestMessage.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestMessage.java @@ -5,25 +5,17 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * An abstract representation of a chat message as provided in a request. */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "role", defaultImpl = ChatRequestMessage.class, visible = true) -@JsonTypeName("ChatRequestMessage") -@JsonSubTypes({ - @JsonSubTypes.Type(name = "system", value = ChatRequestSystemMessage.class), - @JsonSubTypes.Type(name = "user", value = ChatRequestUserMessage.class), - @JsonSubTypes.Type(name = "assistant", value = ChatRequestAssistantMessage.class), - @JsonSubTypes.Type(name = "tool", value = ChatRequestToolMessage.class), - @JsonSubTypes.Type(name = "function", value = ChatRequestFunctionMessage.class) }) @Immutable -public class ChatRequestMessage { +public class ChatRequestMessage implements JsonSerializable { /** * Creates an instance of ChatRequestMessage class. @@ -37,8 +29,6 @@ public ChatRequestMessage() { * The chat role associated with this message. */ @Generated - @JsonTypeId - @JsonProperty(value = "role") private ChatRole role; /** @@ -50,4 +40,75 @@ public ChatRequestMessage() { public ChatRole getRole() { return this.role; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatRequestMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatRequestMessage if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the ChatRequestMessage. + */ + @Generated + public static ChatRequestMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("role".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("system".equals(discriminatorValue)) { + return ChatRequestSystemMessage.fromJson(readerToUse.reset()); + } else if ("user".equals(discriminatorValue)) { + return ChatRequestUserMessage.fromJson(readerToUse.reset()); + } else if ("assistant".equals(discriminatorValue)) { + return ChatRequestAssistantMessage.fromJson(readerToUse.reset()); + } else if ("tool".equals(discriminatorValue)) { + return ChatRequestToolMessage.fromJson(readerToUse.reset()); + } else if ("function".equals(discriminatorValue)) { + return ChatRequestFunctionMessage.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static ChatRequestMessage fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatRequestMessage deserializedChatRequestMessage = new ChatRequestMessage(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("role".equals(fieldName)) { + deserializedChatRequestMessage.role = ChatRole.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedChatRequestMessage; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestSystemMessage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestSystemMessage.java index 9fde1d1d2088c..0a180691c293b 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestSystemMessage.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestSystemMessage.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A request chat message containing system instructions that influence how the model will generate a chat completions * response. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "role", - defaultImpl = ChatRequestSystemMessage.class, - visible = true) -@JsonTypeName("system") @Fluent public final class ChatRequestSystemMessage extends ChatRequestMessage { @@ -28,14 +21,12 @@ public final class ChatRequestSystemMessage extends ChatRequestMessage { * The contents of the system message. */ @Generated - @JsonProperty(value = "content") private final String content; /* * An optional name for the participant. */ @Generated - @JsonProperty(value = "name") private String name; /** @@ -44,8 +35,7 @@ public final class ChatRequestSystemMessage extends ChatRequestMessage { * @param content the content value to set. */ @Generated - @JsonCreator - public ChatRequestSystemMessage(@JsonProperty(value = "content") String content) { + public ChatRequestSystemMessage(String content) { this.content = content; } @@ -85,8 +75,6 @@ public ChatRequestSystemMessage setName(String name) { * The chat role associated with this message. */ @Generated - @JsonTypeId - @JsonProperty(value = "role") private ChatRole role = ChatRole.SYSTEM; /** @@ -99,4 +87,52 @@ public ChatRequestSystemMessage setName(String name) { public ChatRole getRole() { return this.role; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("content", this.content); + jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); + jsonWriter.writeStringField("name", this.name); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatRequestSystemMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatRequestSystemMessage 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 ChatRequestSystemMessage. + */ + @Generated + public static ChatRequestSystemMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String content = null; + ChatRole role = ChatRole.SYSTEM; + String name = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("content".equals(fieldName)) { + content = reader.getString(); + } else if ("role".equals(fieldName)) { + role = ChatRole.fromString(reader.getString()); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatRequestSystemMessage deserializedChatRequestSystemMessage = new ChatRequestSystemMessage(content); + deserializedChatRequestSystemMessage.role = role; + deserializedChatRequestSystemMessage.name = name; + return deserializedChatRequestSystemMessage; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestToolMessage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestToolMessage.java index 9497857963d27..9538f2811ba47 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestToolMessage.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestToolMessage.java @@ -5,17 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A request chat message representing requested output from a configured tool. */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "role", defaultImpl = ChatRequestToolMessage.class, visible = true) -@JsonTypeName("tool") @Immutable public final class ChatRequestToolMessage extends ChatRequestMessage { @@ -23,14 +20,12 @@ public final class ChatRequestToolMessage extends ChatRequestMessage { * The content of the message. */ @Generated - @JsonProperty(value = "content") private final String content; /* * The ID of the tool call resolved by the provided content. */ @Generated - @JsonProperty(value = "tool_call_id") private final String toolCallId; /** @@ -40,9 +35,7 @@ public final class ChatRequestToolMessage extends ChatRequestMessage { * @param toolCallId the toolCallId value to set. */ @Generated - @JsonCreator - public ChatRequestToolMessage(@JsonProperty(value = "content") String content, - @JsonProperty(value = "tool_call_id") String toolCallId) { + public ChatRequestToolMessage(String content, String toolCallId) { this.content = content; this.toolCallId = toolCallId; } @@ -71,8 +64,6 @@ public String getToolCallId() { * The chat role associated with this message. */ @Generated - @JsonTypeId - @JsonProperty(value = "role") private ChatRole role = ChatRole.TOOL; /** @@ -85,4 +76,51 @@ public String getToolCallId() { public ChatRole getRole() { return this.role; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("content", this.content); + jsonWriter.writeStringField("tool_call_id", this.toolCallId); + jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatRequestToolMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatRequestToolMessage 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 ChatRequestToolMessage. + */ + @Generated + public static ChatRequestToolMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String content = null; + String toolCallId = null; + ChatRole role = ChatRole.TOOL; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("content".equals(fieldName)) { + content = reader.getString(); + } else if ("tool_call_id".equals(fieldName)) { + toolCallId = reader.getString(); + } else if ("role".equals(fieldName)) { + role = ChatRole.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + ChatRequestToolMessage deserializedChatRequestToolMessage = new ChatRequestToolMessage(content, toolCallId); + deserializedChatRequestToolMessage.role = role; + return deserializedChatRequestToolMessage; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestUserMessage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestUserMessage.java index 3b1cf1115f651..42a2fbb43508e 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestUserMessage.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestUserMessage.java @@ -6,20 +6,17 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; import com.azure.core.util.BinaryData; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.List; import java.util.stream.Collectors; import java.util.Arrays; -import java.util.List; /** * A request chat message representing user input to the assistant. */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "role", defaultImpl = ChatRequestUserMessage.class, visible = true) -@JsonTypeName("user") @Fluent public final class ChatRequestUserMessage extends ChatRequestMessage { @@ -27,14 +24,12 @@ public final class ChatRequestUserMessage extends ChatRequestMessage { * The contents of the user message, with available input types varying by selected model. */ @Generated - @JsonProperty(value = "content") private final BinaryData content; /* * An optional name for the participant. */ @Generated - @JsonProperty(value = "name") private String name; /** @@ -42,8 +37,7 @@ public final class ChatRequestUserMessage extends ChatRequestMessage { * * @param content the content value to set. */ - @JsonCreator - private ChatRequestUserMessage(@JsonProperty(value = "content") BinaryData content) { + private ChatRequestUserMessage(BinaryData content) { this.content = content; } @@ -110,8 +104,6 @@ public ChatRequestUserMessage setName(String name) { * The chat role associated with this message. */ @Generated - @JsonTypeId - @JsonProperty(value = "role") private ChatRole role = ChatRole.USER; /** @@ -124,4 +116,51 @@ public ChatRequestUserMessage setName(String name) { public ChatRole getRole() { return this.role; } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBinaryField("content", this.content.toBytes()); + jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); + jsonWriter.writeStringField("name", this.name); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatRequestUserMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatRequestUserMessage 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 ChatRequestUserMessage. + */ + @Generated + public static ChatRequestUserMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BinaryData content = null; + ChatRole role = ChatRole.USER; + String name = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("content".equals(fieldName)) { + content = reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())); + } else if ("role".equals(fieldName)) { + role = ChatRole.fromString(reader.getString()); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatRequestUserMessage deserializedChatRequestUserMessage = new ChatRequestUserMessage(content); + deserializedChatRequestUserMessage.role = role; + deserializedChatRequestUserMessage.name = name; + return deserializedChatRequestUserMessage; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatResponseMessage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatResponseMessage.java index af1bda6b34421..51fc2e09e172d 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatResponseMessage.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatResponseMessage.java @@ -5,28 +5,29 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * A representation of a chat message as received in a response. */ @Immutable -public final class ChatResponseMessage { +public final class ChatResponseMessage implements JsonSerializable { /* * The chat role associated with the message. */ @Generated - @JsonProperty(value = "role") private final ChatRole role; /* * The content of the message. */ @Generated - @JsonProperty(value = "content") private final String content; /* @@ -34,7 +35,6 @@ public final class ChatResponseMessage { * completions request to resolve as configured. */ @Generated - @JsonProperty(value = "tool_calls") private List toolCalls; /* @@ -42,7 +42,6 @@ public final class ChatResponseMessage { * completions request to resolve as configured. */ @Generated - @JsonProperty(value = "function_call") private FunctionCall functionCall; /* @@ -50,7 +49,6 @@ public final class ChatResponseMessage { * extensions while processing the chat completions request. */ @Generated - @JsonProperty(value = "context") private AzureChatExtensionsMessageContext context; /** @@ -60,9 +58,7 @@ public final class ChatResponseMessage { * @param content the content value to set. */ @Generated - @JsonCreator - private ChatResponseMessage(@JsonProperty(value = "role") ChatRole role, - @JsonProperty(value = "content") String content) { + private ChatResponseMessage(ChatRole role, String content) { this.role = role; this.content = content; } @@ -122,4 +118,61 @@ public FunctionCall getFunctionCall() { public AzureChatExtensionsMessageContext getContext() { return this.context; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); + jsonWriter.writeStringField("content", this.content); + jsonWriter.writeArrayField("tool_calls", this.toolCalls, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("function_call", this.functionCall); + jsonWriter.writeJsonField("context", this.context); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatResponseMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatResponseMessage 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 ChatResponseMessage. + */ + @Generated + public static ChatResponseMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatRole role = null; + String content = null; + List toolCalls = null; + FunctionCall functionCall = null; + AzureChatExtensionsMessageContext context = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("role".equals(fieldName)) { + role = ChatRole.fromString(reader.getString()); + } else if ("content".equals(fieldName)) { + content = reader.getString(); + } else if ("tool_calls".equals(fieldName)) { + toolCalls = reader.readArray(reader1 -> ChatCompletionsToolCall.fromJson(reader1)); + } else if ("function_call".equals(fieldName)) { + functionCall = FunctionCall.fromJson(reader); + } else if ("context".equals(fieldName)) { + context = AzureChatExtensionsMessageContext.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ChatResponseMessage deserializedChatResponseMessage = new ChatResponseMessage(role, content); + deserializedChatResponseMessage.toolCalls = toolCalls; + deserializedChatResponseMessage.functionCall = functionCall; + deserializedChatResponseMessage.context = context; + return deserializedChatResponseMessage; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRole.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRole.java index c91985b70ab92..a21c71dacb687 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRole.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRole.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -48,7 +47,6 @@ public ChatRole() { * @return the corresponding ChatRole. */ @Generated - @JsonCreator public static ChatRole fromString(String name) { return fromString(name, ChatRole.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatTokenLogProbabilityInfo.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatTokenLogProbabilityInfo.java index 9c221618ed8d4..4ef97794a81b7 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatTokenLogProbabilityInfo.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatTokenLogProbabilityInfo.java @@ -5,35 +5,35 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * A representation of the log probability information for a single message content token. */ @Immutable -public final class ChatTokenLogProbabilityInfo { +public final class ChatTokenLogProbabilityInfo implements JsonSerializable { /* * The message content token. */ @Generated - @JsonProperty(value = "token") private final String token; /* * The log probability of the message content token. */ @Generated - @JsonProperty(value = "logprob") private final double logprob; /* * A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. */ @Generated - @JsonProperty(value = "bytes") private final List bytes; /** @@ -44,9 +44,7 @@ public final class ChatTokenLogProbabilityInfo { * @param bytes the bytes value to set. */ @Generated - @JsonCreator - private ChatTokenLogProbabilityInfo(@JsonProperty(value = "token") String token, - @JsonProperty(value = "logprob") double logprob, @JsonProperty(value = "bytes") List bytes) { + private ChatTokenLogProbabilityInfo(String token, double logprob, List bytes) { this.token = token; this.logprob = logprob; this.bytes = bytes; @@ -83,4 +81,49 @@ public double getLogprob() { public List getBytes() { return this.bytes; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("token", this.token); + jsonWriter.writeDoubleField("logprob", this.logprob); + jsonWriter.writeArrayField("bytes", this.bytes, (writer, element) -> writer.writeInt(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatTokenLogProbabilityInfo from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatTokenLogProbabilityInfo 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 ChatTokenLogProbabilityInfo. + */ + @Generated + public static ChatTokenLogProbabilityInfo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String token = null; + double logprob = 0.0; + List bytes = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("token".equals(fieldName)) { + token = reader.getString(); + } else if ("logprob".equals(fieldName)) { + logprob = reader.getDouble(); + } else if ("bytes".equals(fieldName)) { + bytes = reader.readArray(reader1 -> reader1.getInt()); + } else { + reader.skipChildren(); + } + } + return new ChatTokenLogProbabilityInfo(token, logprob, bytes); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatTokenLogProbabilityResult.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatTokenLogProbabilityResult.java index 2d383cf6d508c..d67212dce73bb 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatTokenLogProbabilityResult.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatTokenLogProbabilityResult.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** @@ -14,34 +17,30 @@ * tokens if 'top_logprobs' were requested. */ @Immutable -public final class ChatTokenLogProbabilityResult { +public final class ChatTokenLogProbabilityResult implements JsonSerializable { /* * The message content token. */ @Generated - @JsonProperty(value = "token") private final String token; /* * The log probability of the message content token. */ @Generated - @JsonProperty(value = "logprob") private final double logprob; /* * A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. */ @Generated - @JsonProperty(value = "bytes") private final List bytes; /* * The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. */ @Generated - @JsonProperty(value = "top_logprobs") private final List topLogprobs; /** @@ -53,10 +52,8 @@ public final class ChatTokenLogProbabilityResult { * @param topLogprobs the topLogprobs value to set. */ @Generated - @JsonCreator - private ChatTokenLogProbabilityResult(@JsonProperty(value = "token") String token, - @JsonProperty(value = "logprob") double logprob, @JsonProperty(value = "bytes") List bytes, - @JsonProperty(value = "top_logprobs") List topLogprobs) { + private ChatTokenLogProbabilityResult(String token, double logprob, List bytes, + List topLogprobs) { this.token = token; this.logprob = logprob; this.bytes = bytes; @@ -105,4 +102,53 @@ public List getBytes() { public List getTopLogprobs() { return this.topLogprobs; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("token", this.token); + jsonWriter.writeDoubleField("logprob", this.logprob); + jsonWriter.writeArrayField("bytes", this.bytes, (writer, element) -> writer.writeInt(element)); + jsonWriter.writeArrayField("top_logprobs", this.topLogprobs, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatTokenLogProbabilityResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatTokenLogProbabilityResult 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 ChatTokenLogProbabilityResult. + */ + @Generated + public static ChatTokenLogProbabilityResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String token = null; + double logprob = 0.0; + List bytes = null; + List topLogprobs = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("token".equals(fieldName)) { + token = reader.getString(); + } else if ("logprob".equals(fieldName)) { + logprob = reader.getDouble(); + } else if ("bytes".equals(fieldName)) { + bytes = reader.readArray(reader1 -> reader1.getInt()); + } else if ("top_logprobs".equals(fieldName)) { + topLogprobs = reader.readArray(reader1 -> ChatTokenLogProbabilityInfo.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + return new ChatTokenLogProbabilityResult(token, logprob, bytes, topLogprobs); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Choice.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Choice.java index ea16f103461c4..b39a34b35a7e2 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Choice.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Choice.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The representation of a single prompt completion as part of an overall completions request. @@ -14,34 +17,30 @@ * Token limits and other settings may limit the number of choices generated. */ @Immutable -public final class Choice { +public final class Choice implements JsonSerializable { /* * The generated text for a given completions prompt. */ @Generated - @JsonProperty(value = "text") private final String text; /* * The ordered index associated with this completions choice. */ @Generated - @JsonProperty(value = "index") private final int index; /* * The log probabilities model for tokens associated with this completions choice. */ @Generated - @JsonProperty(value = "logprobs") private final CompletionsLogProbabilityModel logprobs; /* * Reason for finishing */ @Generated - @JsonProperty(value = "finish_reason") private final CompletionsFinishReason finishReason; /** @@ -53,10 +52,8 @@ public final class Choice { * @param finishReason the finishReason value to set. */ @Generated - @JsonCreator - private Choice(@JsonProperty(value = "text") String text, @JsonProperty(value = "index") int index, - @JsonProperty(value = "logprobs") CompletionsLogProbabilityModel logprobs, - @JsonProperty(value = "finish_reason") CompletionsFinishReason finishReason) { + private Choice(String text, int index, CompletionsLogProbabilityModel logprobs, + CompletionsFinishReason finishReason) { this.text = text; this.index = index; this.logprobs = logprobs; @@ -109,7 +106,6 @@ public CompletionsFinishReason getFinishReason() { * determines the intensity and risk level of harmful content) and if it has been filtered or not. */ @Generated - @JsonProperty(value = "content_filter_results") private ContentFilterResultsForChoice contentFilterResults; /** @@ -124,4 +120,59 @@ public CompletionsFinishReason getFinishReason() { public ContentFilterResultsForChoice getContentFilterResults() { return this.contentFilterResults; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeIntField("index", this.index); + jsonWriter.writeJsonField("logprobs", this.logprobs); + jsonWriter.writeStringField("finish_reason", this.finishReason == null ? null : this.finishReason.toString()); + jsonWriter.writeJsonField("content_filter_results", this.contentFilterResults); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Choice from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Choice 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 Choice. + */ + @Generated + public static Choice fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String text = null; + int index = 0; + CompletionsLogProbabilityModel logprobs = null; + CompletionsFinishReason finishReason = null; + ContentFilterResultsForChoice contentFilterResults = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("text".equals(fieldName)) { + text = reader.getString(); + } else if ("index".equals(fieldName)) { + index = reader.getInt(); + } else if ("logprobs".equals(fieldName)) { + logprobs = CompletionsLogProbabilityModel.fromJson(reader); + } else if ("finish_reason".equals(fieldName)) { + finishReason = CompletionsFinishReason.fromString(reader.getString()); + } else if ("content_filter_results".equals(fieldName)) { + contentFilterResults = ContentFilterResultsForChoice.fromJson(reader); + } else { + reader.skipChildren(); + } + } + Choice deserializedChoice = new Choice(text, index, logprobs, finishReason); + deserializedChoice.contentFilterResults = contentFilterResults; + return deserializedChoice; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Completions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Completions.java index 9628207551349..15d141c189169 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Completions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Completions.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -18,13 +21,12 @@ * provided prompt data. */ @Immutable -public final class Completions { +public final class Completions implements JsonSerializable { /* * A unique identifier associated with this completions response. */ @Generated - @JsonProperty(value = "id") private final String id; /* @@ -33,14 +35,12 @@ public final class Completions { * Token limits and other settings may limit the number of choices generated. */ @Generated - @JsonProperty(value = "choices") private final List choices; /* * Usage information for tokens processed and generated as part of this completions operation. */ @Generated - @JsonProperty(value = "usage") private final CompletionsUsage usage; /** @@ -81,19 +81,8 @@ public CompletionsUsage getUsage() { * results for different prompts may arrive at different times or in different orders. */ @Generated - @JsonProperty(value = "prompt_filter_results") private List promptFilterResults; - /** - * Backing member for the prompt filtering result during the rename transition. More details here - * - * @deprecated This field is only used for deserialization. - */ - @Deprecated - @JsonProperty(value = "prompt_annotations") - private List promptAnnotations; - /** * Get the promptFilterResults property: Content filtering results for zero or more prompts in the request. In a * streaming request, @@ -101,11 +90,9 @@ public CompletionsUsage getUsage() { * * @return the promptFilterResults value. */ + @Generated public List getPromptFilterResults() { - if (this.promptFilterResults != null) { - return this.promptFilterResults; - } - return this.promptAnnotations; + return this.promptFilterResults; } /* @@ -113,7 +100,6 @@ public List getPromptFilterResults() { * represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. */ @Generated - @JsonProperty(value = "created") private final long createdAt; /** @@ -136,13 +122,6 @@ private Completions(String id, OffsetDateTime createdAt, List choices, C this.usage = usage; } - @Generated - @JsonCreator - private Completions(@JsonProperty(value = "id") String id, @JsonProperty(value = "created") long createdAt, - @JsonProperty(value = "choices") List choices, @JsonProperty(value = "usage") CompletionsUsage usage) { - this(id, OffsetDateTime.ofInstant(Instant.ofEpochSecond(createdAt), ZoneOffset.UTC), choices, usage); - } - /** * Get the createdAt property: The first timestamp associated with generation activity for this completions * response, @@ -154,4 +133,60 @@ private Completions(@JsonProperty(value = "id") String id, @JsonProperty(value = public OffsetDateTime getCreatedAt() { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.createdAt), ZoneOffset.UTC); } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeLongField("created", this.createdAt); + jsonWriter.writeArrayField("choices", this.choices, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("usage", this.usage); + jsonWriter.writeArrayField("prompt_filter_results", this.promptFilterResults, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Completions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Completions 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 Completions. + */ + @Generated + public static Completions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + OffsetDateTime createdAt = null; + List choices = null; + CompletionsUsage usage = null; + List promptFilterResults = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("created".equals(fieldName)) { + createdAt = OffsetDateTime.ofInstant(Instant.ofEpochSecond(reader.getLong()), ZoneOffset.UTC); + } else if ("choices".equals(fieldName)) { + choices = reader.readArray(reader1 -> Choice.fromJson(reader1)); + } else if ("usage".equals(fieldName)) { + usage = CompletionsUsage.fromJson(reader); + } else if ("prompt_filter_results".equals(fieldName)) { + promptFilterResults = reader.readArray(reader1 -> ContentFilterResultsForPrompt.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + Completions deserializedCompletions = new Completions(id, createdAt, choices, usage); + deserializedCompletions.promptFilterResults = promptFilterResults; + return deserializedCompletions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsFinishReason.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsFinishReason.java index ed4dd89e2e5f8..e0bf044ac177a 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsFinishReason.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsFinishReason.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -49,7 +48,6 @@ public CompletionsFinishReason() { * @return the corresponding CompletionsFinishReason. */ @Generated - @JsonCreator public static CompletionsFinishReason fromString(String name) { return fromString(name, CompletionsFinishReason.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsLogProbabilityModel.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsLogProbabilityModel.java index 83c895a962f7b..d5ef8ab4d826e 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsLogProbabilityModel.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsLogProbabilityModel.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; import java.util.Map; @@ -14,13 +17,12 @@ * Representation of a log probabilities model for a completions generation. */ @Immutable -public final class CompletionsLogProbabilityModel { +public final class CompletionsLogProbabilityModel implements JsonSerializable { /* * The textual forms of tokens evaluated in this probability model. */ @Generated - @JsonProperty(value = "tokens") private final List tokens; /** @@ -32,11 +34,8 @@ public final class CompletionsLogProbabilityModel { * @param textOffsets the textOffsets value to set. */ @Generated - @JsonCreator - private CompletionsLogProbabilityModel(@JsonProperty(value = "tokens") List tokens, - @JsonProperty(value = "token_logprobs") List tokenLogProbabilities, - @JsonProperty(value = "top_logprobs") List> topLogProbabilities, - @JsonProperty(value = "text_offset") List textOffsets) { + private CompletionsLogProbabilityModel(List tokens, List tokenLogProbabilities, + List> topLogProbabilities, List textOffsets) { this.tokens = tokens; this.tokenLogProbabilities = tokenLogProbabilities; this.topLogProbabilities = topLogProbabilities; @@ -57,21 +56,18 @@ public List getTokens() { * A collection of log probability values for the tokens in this completions data. */ @Generated - @JsonProperty(value = "token_logprobs") private final List tokenLogProbabilities; /* * A mapping of tokens to maximum log probability values in this completions data. */ @Generated - @JsonProperty(value = "top_logprobs") private final List> topLogProbabilities; /* * The text offsets associated with tokens in this completions data. */ @Generated - @JsonProperty(value = "text_offset") private final List textOffsets; /** @@ -105,4 +101,56 @@ public List> getTopLogProbabilities() { public List getTextOffsets() { return this.textOffsets; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("tokens", this.tokens, (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("token_logprobs", this.tokenLogProbabilities, + (writer, element) -> writer.writeDouble(element)); + jsonWriter.writeArrayField("top_logprobs", this.topLogProbabilities, + (writer, element) -> writer.writeMap(element, (writer1, element1) -> writer1.writeNumber(element1))); + jsonWriter.writeArrayField("text_offset", this.textOffsets, (writer, element) -> writer.writeInt(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CompletionsLogProbabilityModel from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CompletionsLogProbabilityModel 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 CompletionsLogProbabilityModel. + */ + @Generated + public static CompletionsLogProbabilityModel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List tokens = null; + List tokenLogProbabilities = null; + List> topLogProbabilities = null; + List textOffsets = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("tokens".equals(fieldName)) { + tokens = reader.readArray(reader1 -> reader1.getString()); + } else if ("token_logprobs".equals(fieldName)) { + tokenLogProbabilities = reader.readArray(reader1 -> reader1.getDouble()); + } else if ("top_logprobs".equals(fieldName)) { + topLogProbabilities = reader + .readArray(reader1 -> reader1.readMap(reader2 -> reader2.getNullable(JsonReader::getDouble))); + } else if ("text_offset".equals(fieldName)) { + textOffsets = reader.readArray(reader1 -> reader1.getInt()); + } else { + reader.skipChildren(); + } + } + return new CompletionsLogProbabilityModel(tokens, tokenLogProbabilities, topLogProbabilities, textOffsets); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsOptions.java index 5b7045e68da06..834df0371c39b 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsOptions.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; import java.util.Map; @@ -16,20 +19,18 @@ * provided prompt data. */ @Fluent -public final class CompletionsOptions { +public final class CompletionsOptions implements JsonSerializable { /* * The prompts to generate completions from. */ @Generated - @JsonProperty(value = "prompt") private final List prompt; /* * The maximum number of tokens to generate. */ @Generated - @JsonProperty(value = "max_tokens") private Integer maxTokens; /* @@ -40,7 +41,6 @@ public final class CompletionsOptions { * interaction of these two settings is difficult to predict. */ @Generated - @JsonProperty(value = "temperature") private Double temperature; /* @@ -52,7 +52,6 @@ public final class CompletionsOptions { * interaction of these two settings is difficult to predict. */ @Generated - @JsonProperty(value = "top_p") private Double topP; /* @@ -63,7 +62,6 @@ public final class CompletionsOptions { * score varies by model. */ @Generated - @JsonProperty(value = "logit_bias") private Map logitBias; /* @@ -71,7 +69,6 @@ public final class CompletionsOptions { * or rate-limiting purposes. */ @Generated - @JsonProperty(value = "user") private String user; /* @@ -81,7 +78,6 @@ public final class CompletionsOptions { * Use carefully and ensure reasonable settings for max_tokens and stop. */ @Generated - @JsonProperty(value = "n") private Integer n; /* @@ -89,7 +85,6 @@ public final class CompletionsOptions { * tokens within a completions response. */ @Generated - @JsonProperty(value = "logprobs") private Integer logprobs; /* @@ -97,14 +92,12 @@ public final class CompletionsOptions { * their generated output. */ @Generated - @JsonProperty(value = "echo") private Boolean echo; /* * A collection of textual sequences that will end completions generation. */ @Generated - @JsonProperty(value = "stop") private List stop; /* @@ -114,7 +107,6 @@ public final class CompletionsOptions { * model's likelihood to output new topics. */ @Generated - @JsonProperty(value = "presence_penalty") private Double presencePenalty; /* @@ -124,7 +116,6 @@ public final class CompletionsOptions { * decrease the likelihood of the model repeating the same statements verbatim. */ @Generated - @JsonProperty(value = "frequency_penalty") private Double frequencyPenalty; /* @@ -136,14 +127,12 @@ public final class CompletionsOptions { * Use carefully and ensure reasonable settings for max_tokens and stop. */ @Generated - @JsonProperty(value = "best_of") private Integer bestOf; /* * A value indicating whether chat completions should be streamed for this request. */ @Generated - @JsonProperty(value = "stream") private Boolean stream; /* @@ -152,7 +141,6 @@ public final class CompletionsOptions { * resource URI that's connected to. */ @Generated - @JsonProperty(value = "model") private String model; /** @@ -161,8 +149,7 @@ public final class CompletionsOptions { * @param prompt the prompt value to set. */ @Generated - @JsonCreator - public CompletionsOptions(@JsonProperty(value = "prompt") List prompt) { + public CompletionsOptions(List prompt) { this.prompt = prompt; } @@ -566,7 +553,6 @@ public CompletionsOptions setModel(String model) { * The suffix that comes after a completion of inserted text */ @Generated - @JsonProperty(value = "suffix") private String suffix; /** @@ -590,4 +576,117 @@ public CompletionsOptions setSuffix(String suffix) { this.suffix = suffix; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("prompt", this.prompt, (writer, element) -> writer.writeString(element)); + jsonWriter.writeNumberField("max_tokens", this.maxTokens); + jsonWriter.writeNumberField("temperature", this.temperature); + jsonWriter.writeNumberField("top_p", this.topP); + jsonWriter.writeMapField("logit_bias", this.logitBias, (writer, element) -> writer.writeInt(element)); + jsonWriter.writeStringField("user", this.user); + jsonWriter.writeNumberField("n", this.n); + jsonWriter.writeNumberField("logprobs", this.logprobs); + jsonWriter.writeStringField("suffix", this.suffix); + jsonWriter.writeBooleanField("echo", this.echo); + jsonWriter.writeArrayField("stop", this.stop, (writer, element) -> writer.writeString(element)); + jsonWriter.writeNumberField("presence_penalty", this.presencePenalty); + jsonWriter.writeNumberField("frequency_penalty", this.frequencyPenalty); + jsonWriter.writeNumberField("best_of", this.bestOf); + jsonWriter.writeBooleanField("stream", this.stream); + jsonWriter.writeStringField("model", this.model); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CompletionsOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CompletionsOptions 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 CompletionsOptions. + */ + @Generated + public static CompletionsOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List prompt = null; + Integer maxTokens = null; + Double temperature = null; + Double topP = null; + Map logitBias = null; + String user = null; + Integer n = null; + Integer logprobs = null; + String suffix = null; + Boolean echo = null; + List stop = null; + Double presencePenalty = null; + Double frequencyPenalty = null; + Integer bestOf = null; + Boolean stream = null; + String model = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("prompt".equals(fieldName)) { + prompt = reader.readArray(reader1 -> reader1.getString()); + } else if ("max_tokens".equals(fieldName)) { + maxTokens = reader.getNullable(JsonReader::getInt); + } else if ("temperature".equals(fieldName)) { + temperature = reader.getNullable(JsonReader::getDouble); + } else if ("top_p".equals(fieldName)) { + topP = reader.getNullable(JsonReader::getDouble); + } else if ("logit_bias".equals(fieldName)) { + logitBias = reader.readMap(reader1 -> reader1.getInt()); + } else if ("user".equals(fieldName)) { + user = reader.getString(); + } else if ("n".equals(fieldName)) { + n = reader.getNullable(JsonReader::getInt); + } else if ("logprobs".equals(fieldName)) { + logprobs = reader.getNullable(JsonReader::getInt); + } else if ("suffix".equals(fieldName)) { + suffix = reader.getString(); + } else if ("echo".equals(fieldName)) { + echo = reader.getNullable(JsonReader::getBoolean); + } else if ("stop".equals(fieldName)) { + stop = reader.readArray(reader1 -> reader1.getString()); + } else if ("presence_penalty".equals(fieldName)) { + presencePenalty = reader.getNullable(JsonReader::getDouble); + } else if ("frequency_penalty".equals(fieldName)) { + frequencyPenalty = reader.getNullable(JsonReader::getDouble); + } else if ("best_of".equals(fieldName)) { + bestOf = reader.getNullable(JsonReader::getInt); + } else if ("stream".equals(fieldName)) { + stream = reader.getNullable(JsonReader::getBoolean); + } else if ("model".equals(fieldName)) { + model = reader.getString(); + } else { + reader.skipChildren(); + } + } + CompletionsOptions deserializedCompletionsOptions = new CompletionsOptions(prompt); + deserializedCompletionsOptions.maxTokens = maxTokens; + deserializedCompletionsOptions.temperature = temperature; + deserializedCompletionsOptions.topP = topP; + deserializedCompletionsOptions.logitBias = logitBias; + deserializedCompletionsOptions.user = user; + deserializedCompletionsOptions.n = n; + deserializedCompletionsOptions.logprobs = logprobs; + deserializedCompletionsOptions.suffix = suffix; + deserializedCompletionsOptions.echo = echo; + deserializedCompletionsOptions.stop = stop; + deserializedCompletionsOptions.presencePenalty = presencePenalty; + deserializedCompletionsOptions.frequencyPenalty = frequencyPenalty; + deserializedCompletionsOptions.bestOf = bestOf; + deserializedCompletionsOptions.stream = stream; + deserializedCompletionsOptions.model = model; + return deserializedCompletionsOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsage.java index e77674b790d49..a5bade071d82a 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsage.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsage.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Representation of the token counts processed for a completions request. @@ -14,27 +17,24 @@ * other consumers. */ @Immutable -public final class CompletionsUsage { +public final class CompletionsUsage implements JsonSerializable { /* * The number of tokens generated across all completions emissions. */ @Generated - @JsonProperty(value = "completion_tokens") private final int completionTokens; /* * The number of tokens in the provided prompts for the completions request. */ @Generated - @JsonProperty(value = "prompt_tokens") private final int promptTokens; /* * The total number of tokens processed for the completions request and response. */ @Generated - @JsonProperty(value = "total_tokens") private final int totalTokens; /** @@ -45,10 +45,7 @@ public final class CompletionsUsage { * @param totalTokens the totalTokens value to set. */ @Generated - @JsonCreator - private CompletionsUsage(@JsonProperty(value = "completion_tokens") int completionTokens, - @JsonProperty(value = "prompt_tokens") int promptTokens, - @JsonProperty(value = "total_tokens") int totalTokens) { + private CompletionsUsage(int completionTokens, int promptTokens, int totalTokens) { this.completionTokens = completionTokens; this.promptTokens = promptTokens; this.totalTokens = totalTokens; @@ -83,4 +80,49 @@ public int getPromptTokens() { public int getTotalTokens() { return this.totalTokens; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("completion_tokens", this.completionTokens); + jsonWriter.writeIntField("prompt_tokens", this.promptTokens); + jsonWriter.writeIntField("total_tokens", this.totalTokens); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CompletionsUsage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CompletionsUsage 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 CompletionsUsage. + */ + @Generated + public static CompletionsUsage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + int completionTokens = 0; + int promptTokens = 0; + int totalTokens = 0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("completion_tokens".equals(fieldName)) { + completionTokens = reader.getInt(); + } else if ("prompt_tokens".equals(fieldName)) { + promptTokens = reader.getInt(); + } else if ("total_tokens".equals(fieldName)) { + totalTokens = reader.getInt(); + } else { + reader.skipChildren(); + } + } + return new CompletionsUsage(completionTokens, promptTokens, totalTokens); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterBlocklistIdResult.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterBlocklistIdResult.java index a463b0f9e13aa..a9c4399634cba 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterBlocklistIdResult.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterBlocklistIdResult.java @@ -5,27 +5,28 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Represents the outcome of an evaluation against a custom blocklist as performed by content filtering. */ @Immutable -public final class ContentFilterBlocklistIdResult { +public final class ContentFilterBlocklistIdResult implements JsonSerializable { /* * The ID of the custom blocklist evaluated. */ @Generated - @JsonProperty(value = "id") private final String id; /* * A value indicating whether or not the content has been filtered. */ @Generated - @JsonProperty(value = "filtered") private final boolean filtered; /** @@ -55,10 +56,49 @@ public boolean isFiltered() { * @param id the id value to set. */ @Generated - @JsonCreator - private ContentFilterBlocklistIdResult(@JsonProperty(value = "filtered") boolean filtered, - @JsonProperty(value = "id") String id) { + private ContentFilterBlocklistIdResult(boolean filtered, String id) { this.filtered = filtered; this.id = id; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("filtered", this.filtered); + jsonWriter.writeStringField("id", this.id); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContentFilterBlocklistIdResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContentFilterBlocklistIdResult 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 ContentFilterBlocklistIdResult. + */ + @Generated + public static ContentFilterBlocklistIdResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean filtered = false; + String id = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("filtered".equals(fieldName)) { + filtered = reader.getBoolean(); + } else if ("id".equals(fieldName)) { + id = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ContentFilterBlocklistIdResult(filtered, id); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterCitedDetectionResult.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterCitedDetectionResult.java index 76dc9271a5d93..fa1c09a7baf81 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterCitedDetectionResult.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterCitedDetectionResult.java @@ -5,41 +5,40 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Represents the outcome of a detection operation against protected resources as performed by content filtering. */ @Immutable -public final class ContentFilterCitedDetectionResult { +public final class ContentFilterCitedDetectionResult implements JsonSerializable { /* * A value indicating whether or not the content has been filtered. */ @Generated - @JsonProperty(value = "filtered") private final boolean filtered; /* * A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. */ @Generated - @JsonProperty(value = "detected") private final boolean detected; /* * The internet location associated with the detection. */ @Generated - @JsonProperty(value = "URL") private String url; /* * The license description associated with the detection. */ @Generated - @JsonProperty(value = "license") private final String license; /** @@ -50,9 +49,7 @@ public final class ContentFilterCitedDetectionResult { * @param license the license value to set. */ @Generated - @JsonCreator - private ContentFilterCitedDetectionResult(@JsonProperty(value = "filtered") boolean filtered, - @JsonProperty(value = "detected") boolean detected, @JsonProperty(value = "license") String license) { + private ContentFilterCitedDetectionResult(boolean filtered, boolean detected, String license) { this.filtered = filtered; this.detected = detected; this.license = license; @@ -98,4 +95,56 @@ public String getUrl() { public String getLicense() { return this.license; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("filtered", this.filtered); + jsonWriter.writeBooleanField("detected", this.detected); + jsonWriter.writeStringField("license", this.license); + jsonWriter.writeStringField("URL", this.url); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContentFilterCitedDetectionResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContentFilterCitedDetectionResult 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 ContentFilterCitedDetectionResult. + */ + @Generated + public static ContentFilterCitedDetectionResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean filtered = false; + boolean detected = false; + String license = null; + String url = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("filtered".equals(fieldName)) { + filtered = reader.getBoolean(); + } else if ("detected".equals(fieldName)) { + detected = reader.getBoolean(); + } else if ("license".equals(fieldName)) { + license = reader.getString(); + } else if ("URL".equals(fieldName)) { + url = reader.getString(); + } else { + reader.skipChildren(); + } + } + ContentFilterCitedDetectionResult deserializedContentFilterCitedDetectionResult + = new ContentFilterCitedDetectionResult(filtered, detected, license); + deserializedContentFilterCitedDetectionResult.url = url; + return deserializedContentFilterCitedDetectionResult; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterDetailedResults.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterDetailedResults.java index ebad041624781..45be140a6febb 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterDetailedResults.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterDetailedResults.java @@ -5,28 +5,29 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * Represents a structured collection of result details for content filtering. */ @Immutable -public final class ContentFilterDetailedResults { +public final class ContentFilterDetailedResults implements JsonSerializable { /* * A value indicating whether or not the content has been filtered. */ @Generated - @JsonProperty(value = "filtered") private final boolean filtered; /* * The collection of detailed blocklist result information. */ @Generated - @JsonProperty(value = "details") private final List details; /** @@ -36,9 +37,7 @@ public final class ContentFilterDetailedResults { * @param details the details value to set. */ @Generated - @JsonCreator - private ContentFilterDetailedResults(@JsonProperty(value = "filtered") boolean filtered, - @JsonProperty(value = "details") List details) { + private ContentFilterDetailedResults(boolean filtered, List details) { this.filtered = filtered; this.details = details; } @@ -62,4 +61,45 @@ public boolean isFiltered() { public List getDetails() { return this.details; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("filtered", this.filtered); + jsonWriter.writeArrayField("details", this.details, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContentFilterDetailedResults from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContentFilterDetailedResults 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 ContentFilterDetailedResults. + */ + @Generated + public static ContentFilterDetailedResults fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean filtered = false; + List details = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("filtered".equals(fieldName)) { + filtered = reader.getBoolean(); + } else if ("details".equals(fieldName)) { + details = reader.readArray(reader1 -> ContentFilterBlocklistIdResult.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + return new ContentFilterDetailedResults(filtered, details); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterDetectionResult.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterDetectionResult.java index d0f49f15da6c9..d3c0fde64a79b 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterDetectionResult.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterDetectionResult.java @@ -5,27 +5,28 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Represents the outcome of a detection operation performed by content filtering. */ @Immutable -public final class ContentFilterDetectionResult { +public final class ContentFilterDetectionResult implements JsonSerializable { /* * A value indicating whether or not the content has been filtered. */ @Generated - @JsonProperty(value = "filtered") private final boolean filtered; /* * A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. */ @Generated - @JsonProperty(value = "detected") private final boolean detected; /** @@ -35,9 +36,7 @@ public final class ContentFilterDetectionResult { * @param detected the detected value to set. */ @Generated - @JsonCreator - private ContentFilterDetectionResult(@JsonProperty(value = "filtered") boolean filtered, - @JsonProperty(value = "detected") boolean detected) { + private ContentFilterDetectionResult(boolean filtered, boolean detected) { this.filtered = filtered; this.detected = detected; } @@ -62,4 +61,45 @@ public boolean isFiltered() { public boolean isDetected() { return this.detected; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("filtered", this.filtered); + jsonWriter.writeBooleanField("detected", this.detected); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContentFilterDetectionResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContentFilterDetectionResult 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 ContentFilterDetectionResult. + */ + @Generated + public static ContentFilterDetectionResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean filtered = false; + boolean detected = false; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("filtered".equals(fieldName)) { + filtered = reader.getBoolean(); + } else if ("detected".equals(fieldName)) { + detected = reader.getBoolean(); + } else { + reader.skipChildren(); + } + } + return new ContentFilterDetectionResult(filtered, detected); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResult.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResult.java index 12230d9aa3c8c..7ebca4351b2cc 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResult.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResult.java @@ -5,27 +5,28 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Information about filtered content severity level and if it has been filtered or not. */ @Immutable -public final class ContentFilterResult { +public final class ContentFilterResult implements JsonSerializable { /* * Ratings for the intensity and risk level of filtered content. */ @Generated - @JsonProperty(value = "severity") private final ContentFilterSeverity severity; /* * A value indicating whether or not the content has been filtered. */ @Generated - @JsonProperty(value = "filtered") private final boolean filtered; /** @@ -55,10 +56,49 @@ public boolean isFiltered() { * @param severity the severity value to set. */ @Generated - @JsonCreator - private ContentFilterResult(@JsonProperty(value = "filtered") boolean filtered, - @JsonProperty(value = "severity") ContentFilterSeverity severity) { + private ContentFilterResult(boolean filtered, ContentFilterSeverity severity) { this.filtered = filtered; this.severity = severity; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("filtered", this.filtered); + jsonWriter.writeStringField("severity", this.severity == null ? null : this.severity.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContentFilterResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContentFilterResult 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 ContentFilterResult. + */ + @Generated + public static ContentFilterResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean filtered = false; + ContentFilterSeverity severity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("filtered".equals(fieldName)) { + filtered = reader.getBoolean(); + } else if ("severity".equals(fieldName)) { + severity = ContentFilterSeverity.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return new ContentFilterResult(filtered, severity); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultDetailsForPrompt.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultDetailsForPrompt.java index 5c81aa94d07ac..280b5181d5fd3 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultDetailsForPrompt.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultDetailsForPrompt.java @@ -6,13 +6,18 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.core.models.ResponseError; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Information about content filtering evaluated against input data to Azure OpenAI. */ @Immutable -public final class ContentFilterResultDetailsForPrompt { +public final class ContentFilterResultDetailsForPrompt + implements JsonSerializable { /* * Describes language related to anatomical organs and genitals, romantic relationships, @@ -21,7 +26,6 @@ public final class ContentFilterResultDetailsForPrompt { * prostitution, pornography, and abuse. */ @Generated - @JsonProperty(value = "sexual") private ContentFilterResult sexual; /* @@ -29,7 +33,6 @@ public final class ContentFilterResultDetailsForPrompt { * kill someone or something; describes weapons, etc. */ @Generated - @JsonProperty(value = "violence") private ContentFilterResult violence; /* @@ -40,7 +43,6 @@ public final class ContentFilterResultDetailsForPrompt { * status, personal appearance, and body size. */ @Generated - @JsonProperty(value = "hate") private ContentFilterResult hate; /* @@ -48,21 +50,18 @@ public final class ContentFilterResultDetailsForPrompt { * or damage one’s body, or kill oneself. */ @Generated - @JsonProperty(value = "self_harm") private ContentFilterResult selfHarm; /* * Describes whether profanity was detected. */ @Generated - @JsonProperty(value = "profanity") private ContentFilterDetectionResult profanity; /* * Describes detection results against configured custom blocklists. */ @Generated - @JsonProperty(value = "custom_blocklists") private ContentFilterDetailedResults customBlocklists; /* @@ -70,14 +69,12 @@ public final class ContentFilterResultDetailsForPrompt { * down or otherwise unable to complete the operation in time. */ @Generated - @JsonProperty(value = "error") private ResponseError error; /* * Whether a jailbreak attempt was detected in the prompt. */ @Generated - @JsonProperty(value = "jailbreak") private ContentFilterDetectionResult jailbreak; /** @@ -181,7 +178,6 @@ private ContentFilterResultDetailsForPrompt() { * Whether an indirect attack was detected in the prompt. */ @Generated - @JsonProperty(value = "indirect_attack") private ContentFilterDetectionResult indirectAttack; /** @@ -193,4 +189,69 @@ private ContentFilterResultDetailsForPrompt() { public ContentFilterDetectionResult getIndirectAttack() { return this.indirectAttack; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("sexual", this.sexual); + jsonWriter.writeJsonField("violence", this.violence); + jsonWriter.writeJsonField("hate", this.hate); + jsonWriter.writeJsonField("self_harm", this.selfHarm); + jsonWriter.writeJsonField("profanity", this.profanity); + jsonWriter.writeJsonField("custom_blocklists", this.customBlocklists); + jsonWriter.writeJsonField("error", this.error); + jsonWriter.writeJsonField("jailbreak", this.jailbreak); + jsonWriter.writeJsonField("indirect_attack", this.indirectAttack); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContentFilterResultDetailsForPrompt from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContentFilterResultDetailsForPrompt if the JsonReader was pointing to an instance of it, + * or null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ContentFilterResultDetailsForPrompt. + */ + @Generated + public static ContentFilterResultDetailsForPrompt fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContentFilterResultDetailsForPrompt deserializedContentFilterResultDetailsForPrompt + = new ContentFilterResultDetailsForPrompt(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("sexual".equals(fieldName)) { + deserializedContentFilterResultDetailsForPrompt.sexual = ContentFilterResult.fromJson(reader); + } else if ("violence".equals(fieldName)) { + deserializedContentFilterResultDetailsForPrompt.violence = ContentFilterResult.fromJson(reader); + } else if ("hate".equals(fieldName)) { + deserializedContentFilterResultDetailsForPrompt.hate = ContentFilterResult.fromJson(reader); + } else if ("self_harm".equals(fieldName)) { + deserializedContentFilterResultDetailsForPrompt.selfHarm = ContentFilterResult.fromJson(reader); + } else if ("profanity".equals(fieldName)) { + deserializedContentFilterResultDetailsForPrompt.profanity + = ContentFilterDetectionResult.fromJson(reader); + } else if ("custom_blocklists".equals(fieldName)) { + deserializedContentFilterResultDetailsForPrompt.customBlocklists + = ContentFilterDetailedResults.fromJson(reader); + } else if ("error".equals(fieldName)) { + deserializedContentFilterResultDetailsForPrompt.error = ResponseError.fromJson(reader); + } else if ("jailbreak".equals(fieldName)) { + deserializedContentFilterResultDetailsForPrompt.jailbreak + = ContentFilterDetectionResult.fromJson(reader); + } else if ("indirect_attack".equals(fieldName)) { + deserializedContentFilterResultDetailsForPrompt.indirectAttack + = ContentFilterDetectionResult.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedContentFilterResultDetailsForPrompt; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultsForChoice.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultsForChoice.java index 43062315a84ca..860d3c9520c9e 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultsForChoice.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultsForChoice.java @@ -6,13 +6,17 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.core.models.ResponseError; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Information about content filtering evaluated against generated model output. */ @Immutable -public final class ContentFilterResultsForChoice { +public final class ContentFilterResultsForChoice implements JsonSerializable { /* * Describes language related to anatomical organs and genitals, romantic relationships, @@ -21,7 +25,6 @@ public final class ContentFilterResultsForChoice { * prostitution, pornography, and abuse. */ @Generated - @JsonProperty(value = "sexual") private ContentFilterResult sexual; /* @@ -29,7 +32,6 @@ public final class ContentFilterResultsForChoice { * kill someone or something; describes weapons, etc. */ @Generated - @JsonProperty(value = "violence") private ContentFilterResult violence; /* @@ -40,7 +42,6 @@ public final class ContentFilterResultsForChoice { * status, personal appearance, and body size. */ @Generated - @JsonProperty(value = "hate") private ContentFilterResult hate; /* @@ -48,21 +49,18 @@ public final class ContentFilterResultsForChoice { * or damage one’s body, or kill oneself. */ @Generated - @JsonProperty(value = "self_harm") private ContentFilterResult selfHarm; /* * Describes whether profanity was detected. */ @Generated - @JsonProperty(value = "profanity") private ContentFilterDetectionResult profanity; /* * Describes detection results against configured custom blocklists. */ @Generated - @JsonProperty(value = "custom_blocklists") private ContentFilterDetailedResults customBlocklists; /* @@ -70,21 +68,18 @@ public final class ContentFilterResultsForChoice { * down or otherwise unable to complete the operation in time. */ @Generated - @JsonProperty(value = "error") private ResponseError error; /* * Information about detection of protected text material. */ @Generated - @JsonProperty(value = "protected_material_text") private ContentFilterDetectionResult protectedMaterialText; /* * Information about detection of protected code material. */ @Generated - @JsonProperty(value = "protected_material_code") private ContentFilterCitedDetectionResult protectedMaterialCode; /** @@ -193,4 +188,68 @@ public ContentFilterDetectionResult getProtectedMaterialText() { public ContentFilterCitedDetectionResult getProtectedMaterialCode() { return this.protectedMaterialCode; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("sexual", this.sexual); + jsonWriter.writeJsonField("violence", this.violence); + jsonWriter.writeJsonField("hate", this.hate); + jsonWriter.writeJsonField("self_harm", this.selfHarm); + jsonWriter.writeJsonField("profanity", this.profanity); + jsonWriter.writeJsonField("custom_blocklists", this.customBlocklists); + jsonWriter.writeJsonField("error", this.error); + jsonWriter.writeJsonField("protected_material_text", this.protectedMaterialText); + jsonWriter.writeJsonField("protected_material_code", this.protectedMaterialCode); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContentFilterResultsForChoice from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContentFilterResultsForChoice if the JsonReader was pointing to an instance of it, or null + * if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ContentFilterResultsForChoice. + */ + @Generated + public static ContentFilterResultsForChoice fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContentFilterResultsForChoice deserializedContentFilterResultsForChoice + = new ContentFilterResultsForChoice(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("sexual".equals(fieldName)) { + deserializedContentFilterResultsForChoice.sexual = ContentFilterResult.fromJson(reader); + } else if ("violence".equals(fieldName)) { + deserializedContentFilterResultsForChoice.violence = ContentFilterResult.fromJson(reader); + } else if ("hate".equals(fieldName)) { + deserializedContentFilterResultsForChoice.hate = ContentFilterResult.fromJson(reader); + } else if ("self_harm".equals(fieldName)) { + deserializedContentFilterResultsForChoice.selfHarm = ContentFilterResult.fromJson(reader); + } else if ("profanity".equals(fieldName)) { + deserializedContentFilterResultsForChoice.profanity = ContentFilterDetectionResult.fromJson(reader); + } else if ("custom_blocklists".equals(fieldName)) { + deserializedContentFilterResultsForChoice.customBlocklists + = ContentFilterDetailedResults.fromJson(reader); + } else if ("error".equals(fieldName)) { + deserializedContentFilterResultsForChoice.error = ResponseError.fromJson(reader); + } else if ("protected_material_text".equals(fieldName)) { + deserializedContentFilterResultsForChoice.protectedMaterialText + = ContentFilterDetectionResult.fromJson(reader); + } else if ("protected_material_code".equals(fieldName)) { + deserializedContentFilterResultsForChoice.protectedMaterialCode + = ContentFilterCitedDetectionResult.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedContentFilterResultsForChoice; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultsForPrompt.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultsForPrompt.java index 9d88c27577ae1..be6e599cb73a7 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultsForPrompt.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterResultsForPrompt.java @@ -5,27 +5,28 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Content filtering results for a single prompt in the request. */ @Immutable -public final class ContentFilterResultsForPrompt { +public final class ContentFilterResultsForPrompt implements JsonSerializable { /* * The index of this prompt in the set of prompt results */ @Generated - @JsonProperty(value = "prompt_index") private final int promptIndex; /* * Content filtering results for this prompt */ @Generated - @JsonProperty(value = "content_filter_results") private final ContentFilterResultDetailsForPrompt contentFilterResults; /** @@ -55,10 +56,49 @@ public ContentFilterResultDetailsForPrompt getContentFilterResults() { * @param contentFilterResults the contentFilterResults value to set. */ @Generated - @JsonCreator - private ContentFilterResultsForPrompt(@JsonProperty(value = "prompt_index") int promptIndex, - @JsonProperty(value = "content_filter_results") ContentFilterResultDetailsForPrompt contentFilterResults) { + private ContentFilterResultsForPrompt(int promptIndex, ContentFilterResultDetailsForPrompt contentFilterResults) { this.promptIndex = promptIndex; this.contentFilterResults = contentFilterResults; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("prompt_index", this.promptIndex); + jsonWriter.writeJsonField("content_filter_results", this.contentFilterResults); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContentFilterResultsForPrompt from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContentFilterResultsForPrompt 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 ContentFilterResultsForPrompt. + */ + @Generated + public static ContentFilterResultsForPrompt fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + int promptIndex = 0; + ContentFilterResultDetailsForPrompt contentFilterResults = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("prompt_index".equals(fieldName)) { + promptIndex = reader.getInt(); + } else if ("content_filter_results".equals(fieldName)) { + contentFilterResults = ContentFilterResultDetailsForPrompt.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new ContentFilterResultsForPrompt(promptIndex, contentFilterResults); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterSeverity.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterSeverity.java index d70af4818be2e..3d51cf39fbe67 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterSeverity.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ContentFilterSeverity.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -63,7 +62,6 @@ public ContentFilterSeverity() { * @return the corresponding ContentFilterSeverity. */ @Generated - @JsonCreator public static ContentFilterSeverity fromString(String name) { return fromString(name, ContentFilterSeverity.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchChatExtensionConfiguration.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchChatExtensionConfiguration.java index 14cc459e5fb70..74804ff0ae8d0 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchChatExtensionConfiguration.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchChatExtensionConfiguration.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat * extension. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = ElasticsearchChatExtensionConfiguration.class, - visible = true) -@JsonTypeName("elasticsearch") @Immutable public final class ElasticsearchChatExtensionConfiguration extends AzureChatExtensionConfiguration { @@ -28,7 +21,6 @@ public final class ElasticsearchChatExtensionConfiguration extends AzureChatExte * The parameters to use when configuring Elasticsearch®. */ @Generated - @JsonProperty(value = "parameters") private final ElasticsearchChatExtensionParameters parameters; /** @@ -47,9 +39,7 @@ public ElasticsearchChatExtensionParameters getParameters() { * @param parameters the parameters value to set. */ @Generated - @JsonCreator - public ElasticsearchChatExtensionConfiguration( - @JsonProperty(value = "parameters") ElasticsearchChatExtensionParameters parameters) { + public ElasticsearchChatExtensionConfiguration(ElasticsearchChatExtensionParameters parameters) { this.parameters = parameters; } @@ -58,8 +48,6 @@ public ElasticsearchChatExtensionConfiguration( * Azure chat extensions are only compatible with Azure OpenAI. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private AzureChatExtensionType type = AzureChatExtensionType.ELASTICSEARCH; /** @@ -74,4 +62,48 @@ public ElasticsearchChatExtensionConfiguration( public AzureChatExtensionType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("parameters", this.parameters); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ElasticsearchChatExtensionConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ElasticsearchChatExtensionConfiguration 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 ElasticsearchChatExtensionConfiguration. + */ + @Generated + public static ElasticsearchChatExtensionConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ElasticsearchChatExtensionParameters parameters = null; + AzureChatExtensionType type = AzureChatExtensionType.ELASTICSEARCH; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("parameters".equals(fieldName)) { + parameters = ElasticsearchChatExtensionParameters.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = AzureChatExtensionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + ElasticsearchChatExtensionConfiguration deserializedElasticsearchChatExtensionConfiguration + = new ElasticsearchChatExtensionConfiguration(parameters); + deserializedElasticsearchChatExtensionConfiguration.type = type; + return deserializedElasticsearchChatExtensionConfiguration; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchChatExtensionParameters.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchChatExtensionParameters.java index 631b144b40605..04977008a9d1f 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchChatExtensionParameters.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchChatExtensionParameters.java @@ -5,15 +5,19 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Parameters to use when configuring Elasticsearch® as an Azure OpenAI chat extension. The supported authentication * types are KeyAndKeyId and EncodedAPIKey. */ @Fluent -public final class ElasticsearchChatExtensionParameters { +public final class ElasticsearchChatExtensionParameters + implements JsonSerializable { /* * The authentication method to use when accessing the defined data source. @@ -23,70 +27,60 @@ public final class ElasticsearchChatExtensionParameters { * authentication. */ @Generated - @JsonProperty(value = "authentication") private OnYourDataAuthenticationOptions authentication; /* * The configured top number of documents to feature for the configured query. */ @Generated - @JsonProperty(value = "top_n_documents") private Integer topNDocuments; /* * Whether queries should be restricted to use of indexed data. */ @Generated - @JsonProperty(value = "in_scope") private Boolean inScope; /* * The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ @Generated - @JsonProperty(value = "strictness") private Integer strictness; /* * Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ @Generated - @JsonProperty(value = "role_information") private String roleInformation; /* * The endpoint of Elasticsearch®. */ @Generated - @JsonProperty(value = "endpoint") private final String endpoint; /* * The index name of Elasticsearch®. */ @Generated - @JsonProperty(value = "index_name") private final String indexName; /* * The index field mapping options of Elasticsearch®. */ @Generated - @JsonProperty(value = "fields_mapping") private ElasticsearchIndexFieldMappingOptions fieldsMapping; /* * The query type of Elasticsearch®. */ @Generated - @JsonProperty(value = "query_type") private ElasticsearchQueryType queryType; /* * The embedding dependency for vector search. */ @Generated - @JsonProperty(value = "embedding_dependency") private OnYourDataVectorizationSource embeddingDependency; /** @@ -96,9 +90,7 @@ public final class ElasticsearchChatExtensionParameters { * @param indexName the indexName value to set. */ @Generated - @JsonCreator - public ElasticsearchChatExtensionParameters(@JsonProperty(value = "endpoint") String endpoint, - @JsonProperty(value = "index_name") String indexName) { + public ElasticsearchChatExtensionParameters(String endpoint, String indexName) { this.endpoint = endpoint; this.indexName = indexName; } @@ -315,4 +307,87 @@ public OnYourDataVectorizationSource getEmbeddingDependency() { this.embeddingDependency = embeddingDependency; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("endpoint", this.endpoint); + jsonWriter.writeStringField("index_name", this.indexName); + jsonWriter.writeJsonField("authentication", this.authentication); + jsonWriter.writeNumberField("top_n_documents", this.topNDocuments); + jsonWriter.writeBooleanField("in_scope", this.inScope); + jsonWriter.writeNumberField("strictness", this.strictness); + jsonWriter.writeStringField("role_information", this.roleInformation); + jsonWriter.writeJsonField("fields_mapping", this.fieldsMapping); + jsonWriter.writeStringField("query_type", this.queryType == null ? null : this.queryType.toString()); + jsonWriter.writeJsonField("embedding_dependency", this.embeddingDependency); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ElasticsearchChatExtensionParameters from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ElasticsearchChatExtensionParameters 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 ElasticsearchChatExtensionParameters. + */ + @Generated + public static ElasticsearchChatExtensionParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String endpoint = null; + String indexName = null; + OnYourDataAuthenticationOptions authentication = null; + Integer topNDocuments = null; + Boolean inScope = null; + Integer strictness = null; + String roleInformation = null; + ElasticsearchIndexFieldMappingOptions fieldsMapping = null; + ElasticsearchQueryType queryType = null; + OnYourDataVectorizationSource embeddingDependency = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("endpoint".equals(fieldName)) { + endpoint = reader.getString(); + } else if ("index_name".equals(fieldName)) { + indexName = reader.getString(); + } else if ("authentication".equals(fieldName)) { + authentication = OnYourDataAuthenticationOptions.fromJson(reader); + } else if ("top_n_documents".equals(fieldName)) { + topNDocuments = reader.getNullable(JsonReader::getInt); + } else if ("in_scope".equals(fieldName)) { + inScope = reader.getNullable(JsonReader::getBoolean); + } else if ("strictness".equals(fieldName)) { + strictness = reader.getNullable(JsonReader::getInt); + } else if ("role_information".equals(fieldName)) { + roleInformation = reader.getString(); + } else if ("fields_mapping".equals(fieldName)) { + fieldsMapping = ElasticsearchIndexFieldMappingOptions.fromJson(reader); + } else if ("query_type".equals(fieldName)) { + queryType = ElasticsearchQueryType.fromString(reader.getString()); + } else if ("embedding_dependency".equals(fieldName)) { + embeddingDependency = OnYourDataVectorizationSource.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ElasticsearchChatExtensionParameters deserializedElasticsearchChatExtensionParameters + = new ElasticsearchChatExtensionParameters(endpoint, indexName); + deserializedElasticsearchChatExtensionParameters.authentication = authentication; + deserializedElasticsearchChatExtensionParameters.topNDocuments = topNDocuments; + deserializedElasticsearchChatExtensionParameters.inScope = inScope; + deserializedElasticsearchChatExtensionParameters.strictness = strictness; + deserializedElasticsearchChatExtensionParameters.roleInformation = roleInformation; + deserializedElasticsearchChatExtensionParameters.fieldsMapping = fieldsMapping; + deserializedElasticsearchChatExtensionParameters.queryType = queryType; + deserializedElasticsearchChatExtensionParameters.embeddingDependency = embeddingDependency; + return deserializedElasticsearchChatExtensionParameters; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchIndexFieldMappingOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchIndexFieldMappingOptions.java index 65bced131e820..e57e184c4be67 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchIndexFieldMappingOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchIndexFieldMappingOptions.java @@ -5,55 +5,54 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * Optional settings to control how fields are processed when using a configured Elasticsearch® resource. */ @Fluent -public final class ElasticsearchIndexFieldMappingOptions { +public final class ElasticsearchIndexFieldMappingOptions + implements JsonSerializable { /* * The name of the index field to use as a title. */ @Generated - @JsonProperty(value = "title_field") private String titleField; /* * The name of the index field to use as a URL. */ @Generated - @JsonProperty(value = "url_field") private String urlField; /* * The name of the index field to use as a filepath. */ @Generated - @JsonProperty(value = "filepath_field") private String filepathField; /* * The names of index fields that should be treated as content. */ @Generated - @JsonProperty(value = "content_fields") private List contentFields; /* * The separator pattern that content fields should use. */ @Generated - @JsonProperty(value = "content_fields_separator") private String contentFieldsSeparator; /* * The names of fields that represent vector data. */ @Generated - @JsonProperty(value = "vector_fields") private List vectorFields; /** @@ -194,4 +193,60 @@ public ElasticsearchIndexFieldMappingOptions setVectorFields(List vector this.vectorFields = vectorFields; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("title_field", this.titleField); + jsonWriter.writeStringField("url_field", this.urlField); + jsonWriter.writeStringField("filepath_field", this.filepathField); + jsonWriter.writeArrayField("content_fields", this.contentFields, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("content_fields_separator", this.contentFieldsSeparator); + jsonWriter.writeArrayField("vector_fields", this.vectorFields, + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ElasticsearchIndexFieldMappingOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ElasticsearchIndexFieldMappingOptions if the JsonReader was pointing to an instance of it, + * or null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ElasticsearchIndexFieldMappingOptions. + */ + @Generated + public static ElasticsearchIndexFieldMappingOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ElasticsearchIndexFieldMappingOptions deserializedElasticsearchIndexFieldMappingOptions + = new ElasticsearchIndexFieldMappingOptions(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("title_field".equals(fieldName)) { + deserializedElasticsearchIndexFieldMappingOptions.titleField = reader.getString(); + } else if ("url_field".equals(fieldName)) { + deserializedElasticsearchIndexFieldMappingOptions.urlField = reader.getString(); + } else if ("filepath_field".equals(fieldName)) { + deserializedElasticsearchIndexFieldMappingOptions.filepathField = reader.getString(); + } else if ("content_fields".equals(fieldName)) { + List contentFields = reader.readArray(reader1 -> reader1.getString()); + deserializedElasticsearchIndexFieldMappingOptions.contentFields = contentFields; + } else if ("content_fields_separator".equals(fieldName)) { + deserializedElasticsearchIndexFieldMappingOptions.contentFieldsSeparator = reader.getString(); + } else if ("vector_fields".equals(fieldName)) { + List vectorFields = reader.readArray(reader1 -> reader1.getString()); + deserializedElasticsearchIndexFieldMappingOptions.vectorFields = vectorFields; + } else { + reader.skipChildren(); + } + } + return deserializedElasticsearchIndexFieldMappingOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchQueryType.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchQueryType.java index ba290abd7f5a2..01d1bbc25e346 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchQueryType.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ElasticsearchQueryType.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -42,7 +41,6 @@ public ElasticsearchQueryType() { * @return the corresponding ElasticsearchQueryType. */ @Generated - @JsonCreator public static ElasticsearchQueryType fromString(String name) { return fromString(name, ElasticsearchQueryType.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingEncodingFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingEncodingFormat.java index 29e22df2aa457..a58954352c783 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingEncodingFormat.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingEncodingFormat.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -42,7 +41,6 @@ class EmbeddingEncodingFormat extends ExpandableStringEnum { private final String embeddingBase64; @@ -49,7 +44,6 @@ public String getEmbeddingAsString() { * Index of the prompt to which the EmbeddingItem corresponds. */ @Generated - @JsonProperty(value = "index") private final int promptIndex; /** @@ -62,17 +56,59 @@ public int getPromptIndex() { return this.promptIndex; } + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("embedding", this.embeddingBase64); + jsonWriter.writeIntField("index", this.promptIndex); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EmbeddingItem from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EmbeddingItem 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 EmbeddingItem. + */ + public static EmbeddingItem fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String embedding = null; + int promptIndex = 0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("embedding".equals(fieldName)) { + embedding = reader.getString(); + } else if ("index".equals(fieldName)) { + promptIndex = reader.getInt(); + } else { + reader.skipChildren(); + } + } + return new EmbeddingItem(embedding, promptIndex); + }); + } + /** * Creates an instance of EmbeddingItem class. * - * @param embedding the embedding value to set. + * @param embeddingBase64 the embedding value to set. * @param promptIndex the promptIndex value to set. */ - @JsonCreator - private EmbeddingItem(@JsonProperty(value = "embedding") BinaryData embedding, - @JsonProperty(value = "index") int promptIndex) { - this.embedding = embedding; + private EmbeddingItem(String embeddingBase64, int promptIndex) { + this.embeddingBase64 = embeddingBase64; this.promptIndex = promptIndex; - embeddingBase64 = embedding.toString(); } + + /* + * List of embeddings value for the input prompt. These represent a measurement of the + * vector-based relatedness of the provided input. + */ + private List embedding; } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Embeddings.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Embeddings.java index 9515820f42a5b..fb5c558d73bc7 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Embeddings.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/Embeddings.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** @@ -15,20 +18,18 @@ * recommendations, and other similar scenarios. */ @Immutable -public final class Embeddings { +public final class Embeddings implements JsonSerializable { /* * Embedding values for the prompts submitted in the request. */ @Generated - @JsonProperty(value = "data") private final List data; /* * Usage counts for tokens input using the embeddings API. */ @Generated - @JsonProperty(value = "usage") private final EmbeddingsUsage usage; /** @@ -38,9 +39,7 @@ public final class Embeddings { * @param usage the usage value to set. */ @Generated - @JsonCreator - private Embeddings(@JsonProperty(value = "data") List data, - @JsonProperty(value = "usage") EmbeddingsUsage usage) { + private Embeddings(List data, EmbeddingsUsage usage) { this.data = data; this.usage = usage; } @@ -64,4 +63,45 @@ public List getData() { public EmbeddingsUsage getUsage() { return this.usage; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("data", this.data, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("usage", this.usage); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Embeddings from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Embeddings 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 Embeddings. + */ + @Generated + public static Embeddings fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List data = null; + EmbeddingsUsage usage = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("data".equals(fieldName)) { + data = reader.readArray(reader1 -> EmbeddingItem.fromJson(reader1)); + } else if ("usage".equals(fieldName)) { + usage = EmbeddingsUsage.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new Embeddings(data, usage); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingsOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingsOptions.java index d6bcbd209c5b6..47d77c38914eb 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingsOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingsOptions.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** @@ -15,14 +18,13 @@ * recommendations, and other similar scenarios. */ @Fluent -public final class EmbeddingsOptions { +public final class EmbeddingsOptions implements JsonSerializable { /* * An identifier for the caller or end user of the operation. This may be used for tracking * or rate-limiting purposes. */ @Generated - @JsonProperty(value = "user") private String user; /* @@ -31,7 +33,6 @@ public final class EmbeddingsOptions { * resource URI that's connected to. */ @Generated - @JsonProperty(value = "model") private String model; /* @@ -42,7 +43,6 @@ public final class EmbeddingsOptions { * as we have observed inferior results when newlines are present. */ @Generated - @JsonProperty(value = "input") private final List input; /** @@ -51,8 +51,7 @@ public final class EmbeddingsOptions { * @param input the input value to set. */ @Generated - @JsonCreator - public EmbeddingsOptions(@JsonProperty(value = "input") List input) { + public EmbeddingsOptions(List input) { this.input = input; } @@ -124,7 +123,6 @@ public List getInput() { * When using Azure OpenAI, specifies the input type to use for embedding search. */ @Generated - @JsonProperty(value = "input_type") private String inputType; /** @@ -153,7 +151,6 @@ public EmbeddingsOptions setInputType(String inputType) { * The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. */ @Generated - @JsonProperty(value = "dimensions") private Integer dimensions; /** @@ -184,7 +181,6 @@ public EmbeddingsOptions setDimensions(Integer dimensions) { * The response encoding format to use for embedding data. */ @Generated - @JsonProperty(value = "encoding_format") private EmbeddingEncodingFormat encodingFormat; /** @@ -208,4 +204,68 @@ EmbeddingsOptions setEncodingFormat(EmbeddingEncodingFormat encodingFormat) { this.encodingFormat = encodingFormat; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("input", this.input, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("user", this.user); + jsonWriter.writeStringField("model", this.model); + jsonWriter.writeStringField("encoding_format", + this.encodingFormat == null ? null : this.encodingFormat.toString()); + jsonWriter.writeNumberField("dimensions", this.dimensions); + jsonWriter.writeStringField("input_type", this.inputType); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EmbeddingsOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EmbeddingsOptions 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 EmbeddingsOptions. + */ + @Generated + public static EmbeddingsOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List input = null; + String user = null; + String model = null; + EmbeddingEncodingFormat encodingFormat = null; + Integer dimensions = null; + String inputType = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("input".equals(fieldName)) { + input = reader.readArray(reader1 -> reader1.getString()); + } else if ("user".equals(fieldName)) { + user = reader.getString(); + } else if ("model".equals(fieldName)) { + model = reader.getString(); + } else if ("encoding_format".equals(fieldName)) { + encodingFormat = EmbeddingEncodingFormat.fromString(reader.getString()); + } else if ("dimensions".equals(fieldName)) { + dimensions = reader.getNullable(JsonReader::getInt); + } else if ("input_type".equals(fieldName)) { + inputType = reader.getString(); + } else { + reader.skipChildren(); + } + } + EmbeddingsOptions deserializedEmbeddingsOptions = new EmbeddingsOptions(input); + deserializedEmbeddingsOptions.user = user; + deserializedEmbeddingsOptions.model = model; + deserializedEmbeddingsOptions.encodingFormat = encodingFormat; + deserializedEmbeddingsOptions.dimensions = dimensions; + deserializedEmbeddingsOptions.inputType = inputType; + return deserializedEmbeddingsOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingsUsage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingsUsage.java index 111c7869619ad..cb8808d3987d6 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingsUsage.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/EmbeddingsUsage.java @@ -5,27 +5,28 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Measurement of the amount of tokens used in this request and response. */ @Immutable -public final class EmbeddingsUsage { +public final class EmbeddingsUsage implements JsonSerializable { /* * Number of tokens sent in the original request. */ @Generated - @JsonProperty(value = "prompt_tokens") private final int promptTokens; /* * Total number of tokens transacted in this request/response. */ @Generated - @JsonProperty(value = "total_tokens") private final int totalTokens; /** @@ -35,9 +36,7 @@ public final class EmbeddingsUsage { * @param totalTokens the totalTokens value to set. */ @Generated - @JsonCreator - private EmbeddingsUsage(@JsonProperty(value = "prompt_tokens") int promptTokens, - @JsonProperty(value = "total_tokens") int totalTokens) { + private EmbeddingsUsage(int promptTokens, int totalTokens) { this.promptTokens = promptTokens; this.totalTokens = totalTokens; } @@ -61,4 +60,45 @@ public int getPromptTokens() { public int getTotalTokens() { return this.totalTokens; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("prompt_tokens", this.promptTokens); + jsonWriter.writeIntField("total_tokens", this.totalTokens); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EmbeddingsUsage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EmbeddingsUsage 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 EmbeddingsUsage. + */ + @Generated + public static EmbeddingsUsage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + int promptTokens = 0; + int totalTokens = 0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("prompt_tokens".equals(fieldName)) { + promptTokens = reader.getInt(); + } else if ("total_tokens".equals(fieldName)) { + totalTokens = reader.getInt(); + } else { + reader.skipChildren(); + } + } + return new EmbeddingsUsage(promptTokens, totalTokens); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionCall.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionCall.java index ee38290a971f5..14ff2ca7e521a 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionCall.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionCall.java @@ -5,20 +5,22 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The name and arguments of a function that should be called, as generated by the model. */ @Immutable -public final class FunctionCall { +public final class FunctionCall implements JsonSerializable { /* * The name of the function to call. */ @Generated - @JsonProperty(value = "name") private final String name; /* @@ -28,7 +30,6 @@ public final class FunctionCall { * your function. */ @Generated - @JsonProperty(value = "arguments") private final String arguments; /** @@ -38,9 +39,7 @@ public final class FunctionCall { * @param arguments the arguments value to set. */ @Generated - @JsonCreator - public FunctionCall(@JsonProperty(value = "name") String name, - @JsonProperty(value = "arguments") String arguments) { + public FunctionCall(String name, String arguments) { this.name = name; this.arguments = arguments; } @@ -67,4 +66,45 @@ public String getName() { public String getArguments() { return this.arguments; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("arguments", this.arguments); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FunctionCall from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FunctionCall 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 FunctionCall. + */ + @Generated + public static FunctionCall fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + String arguments = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("arguments".equals(fieldName)) { + arguments = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new FunctionCall(name, arguments); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionDefinition.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionDefinition.java index 7a5bbf9dd8073..87db18df732b9 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionDefinition.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionDefinition.java @@ -5,21 +5,23 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import com.azure.core.util.BinaryData; /** * The definition of a caller-specified function that chat completions may invoke in response to matching user input. */ @Fluent -public final class FunctionDefinition { +public final class FunctionDefinition implements JsonSerializable { /* * The name of the function to be called. */ @Generated - @JsonProperty(value = "name") private final String name; /* @@ -27,13 +29,11 @@ public final class FunctionDefinition { * interpreting its parameters. */ @Generated - @JsonProperty(value = "description") private String description; /* * The parameters the function accepts, described as a JSON Schema object. */ - @JsonProperty(value = "parameters") private BinaryData parameters; /** @@ -42,8 +42,7 @@ public final class FunctionDefinition { * @param name the name value to set. */ @Generated - @JsonCreator - public FunctionDefinition(@JsonProperty(value = "name") String name) { + public FunctionDefinition(String name) { this.name = name; } @@ -102,4 +101,50 @@ public FunctionDefinition setParameters(BinaryData parameters) { this.parameters = parameters; return this; } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeRawField("parameters", this.parameters.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FunctionDefinition from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FunctionDefinition 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 FunctionDefinition. + */ + public static FunctionDefinition fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + String description = null; + BinaryData parameters = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else if ("parameters".equals(fieldName)) { + parameters = BinaryData.fromObject(reader.readUntyped()); + } else { + reader.skipChildren(); + } + } + FunctionDefinition deserializedFunctionDefinition = new FunctionDefinition(name); + deserializedFunctionDefinition.description = description; + deserializedFunctionDefinition.parameters = parameters; + return deserializedFunctionDefinition; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionName.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionName.java index 60c5390d30339..cfa4e11f4b851 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionName.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/FunctionName.java @@ -5,21 +5,23 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A structure that specifies the exact name of a specific, request-provided function to use when processing a chat * completions operation. */ @Immutable -public final class FunctionName { +public final class FunctionName implements JsonSerializable { /* * The name of the function to call. */ @Generated - @JsonProperty(value = "name") private final String name; /** @@ -28,8 +30,7 @@ public final class FunctionName { * @param name the name value to set. */ @Generated - @JsonCreator - public FunctionName(@JsonProperty(value = "name") String name) { + public FunctionName(String name) { this.name = name; } @@ -42,4 +43,41 @@ public FunctionName(@JsonProperty(value = "name") String name) { public String getName() { return this.name; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FunctionName from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FunctionName 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 FunctionName. + */ + @Generated + public static FunctionName fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + name = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new FunctionName(name); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationContentFilterResults.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationContentFilterResults.java index 9589dabed0930..1de4f44c83da3 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationContentFilterResults.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationContentFilterResults.java @@ -5,13 +5,18 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Describes the content filtering result for the image generation request. */ @Immutable -public final class ImageGenerationContentFilterResults { +public final class ImageGenerationContentFilterResults + implements JsonSerializable { /* * Describes language related to anatomical organs and genitals, romantic relationships, @@ -20,7 +25,6 @@ public final class ImageGenerationContentFilterResults { * prostitution, pornography, and abuse. */ @Generated - @JsonProperty(value = "sexual") private ContentFilterResult sexual; /* @@ -28,7 +32,6 @@ public final class ImageGenerationContentFilterResults { * kill someone or something; describes weapons, etc. */ @Generated - @JsonProperty(value = "violence") private ContentFilterResult violence; /* @@ -39,7 +42,6 @@ public final class ImageGenerationContentFilterResults { * status, personal appearance, and body size. */ @Generated - @JsonProperty(value = "hate") private ContentFilterResult hate; /* @@ -47,7 +49,6 @@ public final class ImageGenerationContentFilterResults { * or damage one’s body, or kill oneself. */ @Generated - @JsonProperty(value = "self_harm") private ContentFilterResult selfHarm; /** @@ -105,4 +106,50 @@ public ContentFilterResult getHate() { public ContentFilterResult getSelfHarm() { return this.selfHarm; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("sexual", this.sexual); + jsonWriter.writeJsonField("violence", this.violence); + jsonWriter.writeJsonField("hate", this.hate); + jsonWriter.writeJsonField("self_harm", this.selfHarm); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImageGenerationContentFilterResults from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImageGenerationContentFilterResults if the JsonReader was pointing to an instance of it, + * or null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ImageGenerationContentFilterResults. + */ + @Generated + public static ImageGenerationContentFilterResults fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImageGenerationContentFilterResults deserializedImageGenerationContentFilterResults + = new ImageGenerationContentFilterResults(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("sexual".equals(fieldName)) { + deserializedImageGenerationContentFilterResults.sexual = ContentFilterResult.fromJson(reader); + } else if ("violence".equals(fieldName)) { + deserializedImageGenerationContentFilterResults.violence = ContentFilterResult.fromJson(reader); + } else if ("hate".equals(fieldName)) { + deserializedImageGenerationContentFilterResults.hate = ContentFilterResult.fromJson(reader); + } else if ("self_harm".equals(fieldName)) { + deserializedImageGenerationContentFilterResults.selfHarm = ContentFilterResult.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedImageGenerationContentFilterResults; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationData.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationData.java index 7bb93f4d925dc..453c6ddf11612 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationData.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationData.java @@ -5,27 +5,29 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A representation of a single generated image, provided as either base64-encoded data or as a URL from which the image * may be retrieved. */ @Immutable -public final class ImageGenerationData { +public final class ImageGenerationData implements JsonSerializable { /* * The URL that provides temporary access to download the generated image. */ @Generated - @JsonProperty(value = "url") private String url; /* * The complete data for an image, represented as a base64-encoded string. */ @Generated - @JsonProperty(value = "b64_json") private String base64Data; /* @@ -33,7 +35,6 @@ public final class ImageGenerationData { * Only provided with dall-3-models and only when revisions were made to the prompt. */ @Generated - @JsonProperty(value = "revised_prompt") private String revisedPrompt; /** @@ -78,7 +79,6 @@ public String getRevisedPrompt() { * Information about the content filtering results. */ @Generated - @JsonProperty(value = "content_filter_results") private ImageGenerationContentFilterResults contentFilterResults; /* @@ -90,7 +90,6 @@ public String getRevisedPrompt() { * been filtered and its id. */ @Generated - @JsonProperty(value = "prompt_filter_results") private ImageGenerationPromptFilterResults promptFilterResults; /** @@ -118,4 +117,54 @@ public ImageGenerationContentFilterResults getContentFilterResults() { public ImageGenerationPromptFilterResults getPromptFilterResults() { return this.promptFilterResults; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("b64_json", this.base64Data); + jsonWriter.writeJsonField("content_filter_results", this.contentFilterResults); + jsonWriter.writeStringField("revised_prompt", this.revisedPrompt); + jsonWriter.writeJsonField("prompt_filter_results", this.promptFilterResults); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImageGenerationData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImageGenerationData if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the ImageGenerationData. + */ + @Generated + public static ImageGenerationData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImageGenerationData deserializedImageGenerationData = new ImageGenerationData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("url".equals(fieldName)) { + deserializedImageGenerationData.url = reader.getString(); + } else if ("b64_json".equals(fieldName)) { + deserializedImageGenerationData.base64Data = reader.getString(); + } else if ("content_filter_results".equals(fieldName)) { + deserializedImageGenerationData.contentFilterResults + = ImageGenerationContentFilterResults.fromJson(reader); + } else if ("revised_prompt".equals(fieldName)) { + deserializedImageGenerationData.revisedPrompt = reader.getString(); + } else if ("prompt_filter_results".equals(fieldName)) { + deserializedImageGenerationData.promptFilterResults + = ImageGenerationPromptFilterResults.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedImageGenerationData; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationOptions.java index 1127be71257cc..53a669f762c2a 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationOptions.java @@ -5,20 +5,22 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Represents the request data used to generate images. */ @Fluent -public final class ImageGenerationOptions { +public final class ImageGenerationOptions implements JsonSerializable { /* * A description of the desired images. */ @Generated - @JsonProperty(value = "prompt") private final String prompt; /* @@ -27,7 +29,6 @@ public final class ImageGenerationOptions { * Dall-e-3 models only support a value of 1. */ @Generated - @JsonProperty(value = "n") private Integer n; /* @@ -36,14 +37,12 @@ public final class ImageGenerationOptions { * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. */ @Generated - @JsonProperty(value = "size") private ImageSize size; /* * A unique identifier representing your end-user, which can help to monitor and detect abuse. */ @Generated - @JsonProperty(value = "user") private String user; /** @@ -52,8 +51,7 @@ public final class ImageGenerationOptions { * @param prompt the prompt value to set. */ @Generated - @JsonCreator - public ImageGenerationOptions(@JsonProperty(value = "prompt") String prompt) { + public ImageGenerationOptions(String prompt) { this.prompt = prompt; } @@ -147,7 +145,6 @@ public ImageGenerationOptions setUser(String user) { * The format in which image generation response items should be presented. */ @Generated - @JsonProperty(value = "response_format") private ImageGenerationResponseFormat responseFormat; /** @@ -177,7 +174,6 @@ public ImageGenerationOptions setResponseFormat(ImageGenerationResponseFormat re * inferred as a default. */ @Generated - @JsonProperty(value = "model") private String model; /* @@ -185,7 +181,6 @@ public ImageGenerationOptions setResponseFormat(ImageGenerationResponseFormat re * Only configurable with dall-e-3 models. */ @Generated - @JsonProperty(value = "quality") private ImageGenerationQuality quality; /* @@ -193,7 +188,6 @@ public ImageGenerationOptions setResponseFormat(ImageGenerationResponseFormat re * Only configurable with dall-e-3 models. */ @Generated - @JsonProperty(value = "style") private ImageGenerationStyle style; /** @@ -269,4 +263,78 @@ public ImageGenerationOptions setStyle(ImageGenerationStyle style) { this.style = style; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("prompt", this.prompt); + jsonWriter.writeStringField("model", this.model); + jsonWriter.writeNumberField("n", this.n); + jsonWriter.writeStringField("size", this.size == null ? null : this.size.toString()); + jsonWriter.writeStringField("response_format", + this.responseFormat == null ? null : this.responseFormat.toString()); + jsonWriter.writeStringField("quality", this.quality == null ? null : this.quality.toString()); + jsonWriter.writeStringField("style", this.style == null ? null : this.style.toString()); + jsonWriter.writeStringField("user", this.user); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImageGenerationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImageGenerationOptions 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 ImageGenerationOptions. + */ + @Generated + public static ImageGenerationOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String prompt = null; + String model = null; + Integer n = null; + ImageSize size = null; + ImageGenerationResponseFormat responseFormat = null; + ImageGenerationQuality quality = null; + ImageGenerationStyle style = null; + String user = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("prompt".equals(fieldName)) { + prompt = reader.getString(); + } else if ("model".equals(fieldName)) { + model = reader.getString(); + } else if ("n".equals(fieldName)) { + n = reader.getNullable(JsonReader::getInt); + } else if ("size".equals(fieldName)) { + size = ImageSize.fromString(reader.getString()); + } else if ("response_format".equals(fieldName)) { + responseFormat = ImageGenerationResponseFormat.fromString(reader.getString()); + } else if ("quality".equals(fieldName)) { + quality = ImageGenerationQuality.fromString(reader.getString()); + } else if ("style".equals(fieldName)) { + style = ImageGenerationStyle.fromString(reader.getString()); + } else if ("user".equals(fieldName)) { + user = reader.getString(); + } else { + reader.skipChildren(); + } + } + ImageGenerationOptions deserializedImageGenerationOptions = new ImageGenerationOptions(prompt); + deserializedImageGenerationOptions.model = model; + deserializedImageGenerationOptions.n = n; + deserializedImageGenerationOptions.size = size; + deserializedImageGenerationOptions.responseFormat = responseFormat; + deserializedImageGenerationOptions.quality = quality; + deserializedImageGenerationOptions.style = style; + deserializedImageGenerationOptions.user = user; + return deserializedImageGenerationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationPromptFilterResults.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationPromptFilterResults.java index 82b38408fdd5d..05db2197c62c1 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationPromptFilterResults.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationPromptFilterResults.java @@ -5,13 +5,17 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Describes the content filtering results for the prompt of a image generation request. */ @Immutable -public final class ImageGenerationPromptFilterResults { +public final class ImageGenerationPromptFilterResults implements JsonSerializable { /* * Describes language related to anatomical organs and genitals, romantic relationships, @@ -20,7 +24,6 @@ public final class ImageGenerationPromptFilterResults { * prostitution, pornography, and abuse. */ @Generated - @JsonProperty(value = "sexual") private ContentFilterResult sexual; /* @@ -28,7 +31,6 @@ public final class ImageGenerationPromptFilterResults { * kill someone or something; describes weapons, etc. */ @Generated - @JsonProperty(value = "violence") private ContentFilterResult violence; /* @@ -39,7 +41,6 @@ public final class ImageGenerationPromptFilterResults { * status, personal appearance, and body size. */ @Generated - @JsonProperty(value = "hate") private ContentFilterResult hate; /* @@ -47,21 +48,18 @@ public final class ImageGenerationPromptFilterResults { * or damage one’s body, or kill oneself. */ @Generated - @JsonProperty(value = "self_harm") private ContentFilterResult selfHarm; /* * Describes whether profanity was detected. */ @Generated - @JsonProperty(value = "profanity") private ContentFilterDetectionResult profanity; /* * Whether a jailbreak attempt was detected in the prompt. */ @Generated - @JsonProperty(value = "jailbreak") private ContentFilterDetectionResult jailbreak; /** @@ -139,4 +137,58 @@ public ContentFilterDetectionResult getProfanity() { public ContentFilterDetectionResult getJailbreak() { return this.jailbreak; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("sexual", this.sexual); + jsonWriter.writeJsonField("violence", this.violence); + jsonWriter.writeJsonField("hate", this.hate); + jsonWriter.writeJsonField("self_harm", this.selfHarm); + jsonWriter.writeJsonField("profanity", this.profanity); + jsonWriter.writeJsonField("jailbreak", this.jailbreak); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImageGenerationPromptFilterResults from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImageGenerationPromptFilterResults if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the ImageGenerationPromptFilterResults. + */ + @Generated + public static ImageGenerationPromptFilterResults fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImageGenerationPromptFilterResults deserializedImageGenerationPromptFilterResults + = new ImageGenerationPromptFilterResults(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("sexual".equals(fieldName)) { + deserializedImageGenerationPromptFilterResults.sexual = ContentFilterResult.fromJson(reader); + } else if ("violence".equals(fieldName)) { + deserializedImageGenerationPromptFilterResults.violence = ContentFilterResult.fromJson(reader); + } else if ("hate".equals(fieldName)) { + deserializedImageGenerationPromptFilterResults.hate = ContentFilterResult.fromJson(reader); + } else if ("self_harm".equals(fieldName)) { + deserializedImageGenerationPromptFilterResults.selfHarm = ContentFilterResult.fromJson(reader); + } else if ("profanity".equals(fieldName)) { + deserializedImageGenerationPromptFilterResults.profanity + = ContentFilterDetectionResult.fromJson(reader); + } else if ("jailbreak".equals(fieldName)) { + deserializedImageGenerationPromptFilterResults.jailbreak + = ContentFilterDetectionResult.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedImageGenerationPromptFilterResults; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationQuality.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationQuality.java index d91ea9c699db4..2cadcc1ff306e 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationQuality.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationQuality.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -43,7 +42,6 @@ public ImageGenerationQuality() { * @return the corresponding ImageGenerationQuality. */ @Generated - @JsonCreator public static ImageGenerationQuality fromString(String name) { return fromString(name, ImageGenerationQuality.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationResponseFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationResponseFormat.java index 16fbf96edf99a..10cce37f2a7a9 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationResponseFormat.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationResponseFormat.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -42,7 +41,6 @@ public ImageGenerationResponseFormat() { * @return the corresponding ImageGenerationResponseFormat. */ @Generated - @JsonCreator public static ImageGenerationResponseFormat fromString(String name) { return fromString(name, ImageGenerationResponseFormat.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationStyle.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationStyle.java index e718b13ffe028..f3a19ece9c985 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationStyle.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerationStyle.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -46,7 +45,6 @@ public ImageGenerationStyle() { * @return the corresponding ImageGenerationStyle. */ @Generated - @JsonCreator public static ImageGenerationStyle fromString(String name) { return fromString(name, ImageGenerationStyle.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerations.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerations.java index e6bf4779f0b41..a41f6170a9513 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerations.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageGenerations.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -16,21 +19,19 @@ * The result of a successful image generation operation. */ @Immutable -public final class ImageGenerations { +public final class ImageGenerations implements JsonSerializable { /* * A timestamp representing when this operation was started. * Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. */ @Generated - @JsonProperty(value = "created") private final long createdAt; /* * The images generated by the operation. */ @Generated - @JsonProperty(value = "data") private final List data; /** @@ -49,13 +50,6 @@ private ImageGenerations(OffsetDateTime createdAt, List dat this.data = data; } - @Generated - @JsonCreator - private ImageGenerations(@JsonProperty(value = "created") long createdAt, - @JsonProperty(value = "data") List data) { - this(OffsetDateTime.ofInstant(Instant.ofEpochSecond(createdAt), ZoneOffset.UTC), data); - } - /** * Get the createdAt property: A timestamp representing when this operation was started. * Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. @@ -76,4 +70,45 @@ public OffsetDateTime getCreatedAt() { public List getData() { return this.data; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeLongField("created", this.createdAt); + jsonWriter.writeArrayField("data", this.data, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImageGenerations from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImageGenerations 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 ImageGenerations. + */ + @Generated + public static ImageGenerations fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime createdAt = null; + List data = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("created".equals(fieldName)) { + createdAt = OffsetDateTime.ofInstant(Instant.ofEpochSecond(reader.getLong()), ZoneOffset.UTC); + } else if ("data".equals(fieldName)) { + data = reader.readArray(reader1 -> ImageGenerationData.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + return new ImageGenerations(createdAt, data); + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageSize.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageSize.java index 87a3be532d2d7..06a70b3390332 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageSize.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ImageSize.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -51,7 +50,6 @@ public ImageSize() { * @return the corresponding ImageSize. */ @Generated - @JsonCreator public static ImageSize fromString(String name) { return fromString(name, ImageSize.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/MaxTokensFinishDetails.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/MaxTokensFinishDetails.java index 60c354d0f91e6..c8b66788132bc 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/MaxTokensFinishDetails.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/MaxTokensFinishDetails.java @@ -5,18 +5,16 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A structured representation of a stop reason that signifies a token limit was reached before the model could * naturally * complete. */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = MaxTokensFinishDetails.class, visible = true) -@JsonTypeName("max_tokens") @Immutable public final class MaxTokensFinishDetails extends ChatFinishDetails { @@ -31,8 +29,6 @@ private MaxTokensFinishDetails() { * The object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type = "max_tokens"; /** @@ -45,4 +41,40 @@ private MaxTokensFinishDetails() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MaxTokensFinishDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MaxTokensFinishDetails if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IOException If an error occurs while reading the MaxTokensFinishDetails. + */ + @Generated + public static MaxTokensFinishDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + MaxTokensFinishDetails deserializedMaxTokensFinishDetails = new MaxTokensFinishDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedMaxTokensFinishDetails.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedMaxTokensFinishDetails; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAccessTokenAuthenticationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAccessTokenAuthenticationOptions.java index 03f318577af1d..3b42b9ae31973 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAccessTokenAuthenticationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAccessTokenAuthenticationOptions.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The authentication options for Azure OpenAI On Your Data when using access token. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataAccessTokenAuthenticationOptions.class, - visible = true) -@JsonTypeName("access_token") @Immutable public final class OnYourDataAccessTokenAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -27,7 +20,6 @@ public final class OnYourDataAccessTokenAuthenticationOptions extends OnYourData * The access token to use for authentication. */ @Generated - @JsonProperty(value = "access_token") private final String accessToken; /** @@ -36,8 +28,7 @@ public final class OnYourDataAccessTokenAuthenticationOptions extends OnYourData * @param accessToken the accessToken value to set. */ @Generated - @JsonCreator - public OnYourDataAccessTokenAuthenticationOptions(@JsonProperty(value = "access_token") String accessToken) { + public OnYourDataAccessTokenAuthenticationOptions(String accessToken) { this.accessToken = accessToken; } @@ -55,8 +46,6 @@ public String getAccessToken() { * The authentication type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataAuthenticationType type = OnYourDataAuthenticationType.ACCESS_TOKEN; /** @@ -69,4 +58,48 @@ public String getAccessToken() { public OnYourDataAuthenticationType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("access_token", this.accessToken); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataAccessTokenAuthenticationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataAccessTokenAuthenticationOptions 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 OnYourDataAccessTokenAuthenticationOptions. + */ + @Generated + public static OnYourDataAccessTokenAuthenticationOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String accessToken = null; + OnYourDataAuthenticationType type = OnYourDataAuthenticationType.ACCESS_TOKEN; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("access_token".equals(fieldName)) { + accessToken = reader.getString(); + } else if ("type".equals(fieldName)) { + type = OnYourDataAuthenticationType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + OnYourDataAccessTokenAuthenticationOptions deserializedOnYourDataAccessTokenAuthenticationOptions + = new OnYourDataAccessTokenAuthenticationOptions(accessToken); + deserializedOnYourDataAccessTokenAuthenticationOptions.type = type; + return deserializedOnYourDataAccessTokenAuthenticationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataApiKeyAuthenticationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataApiKeyAuthenticationOptions.java index 647011d9e135b..44812dc9aaa3e 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataApiKeyAuthenticationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataApiKeyAuthenticationOptions.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The authentication options for Azure OpenAI On Your Data when using an API key. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataApiKeyAuthenticationOptions.class, - visible = true) -@JsonTypeName("api_key") @Immutable public final class OnYourDataApiKeyAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -27,7 +20,6 @@ public final class OnYourDataApiKeyAuthenticationOptions extends OnYourDataAuthe * The API key to use for authentication. */ @Generated - @JsonProperty(value = "key") private final String key; /** @@ -36,8 +28,7 @@ public final class OnYourDataApiKeyAuthenticationOptions extends OnYourDataAuthe * @param key the key value to set. */ @Generated - @JsonCreator - public OnYourDataApiKeyAuthenticationOptions(@JsonProperty(value = "key") String key) { + public OnYourDataApiKeyAuthenticationOptions(String key) { this.key = key; } @@ -55,8 +46,6 @@ public String getKey() { * The authentication type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataAuthenticationType type = OnYourDataAuthenticationType.API_KEY; /** @@ -69,4 +58,48 @@ public String getKey() { public OnYourDataAuthenticationType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("key", this.key); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataApiKeyAuthenticationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataApiKeyAuthenticationOptions 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 OnYourDataApiKeyAuthenticationOptions. + */ + @Generated + public static OnYourDataApiKeyAuthenticationOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String key = null; + OnYourDataAuthenticationType type = OnYourDataAuthenticationType.API_KEY; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("key".equals(fieldName)) { + key = reader.getString(); + } else if ("type".equals(fieldName)) { + type = OnYourDataAuthenticationType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + OnYourDataApiKeyAuthenticationOptions deserializedOnYourDataApiKeyAuthenticationOptions + = new OnYourDataApiKeyAuthenticationOptions(key); + deserializedOnYourDataApiKeyAuthenticationOptions.type = type; + return deserializedOnYourDataApiKeyAuthenticationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAuthenticationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAuthenticationOptions.java index 083d3821c3574..27e849ec83ae9 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAuthenticationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAuthenticationOptions.java @@ -5,35 +5,17 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The authentication options for Azure OpenAI On Your Data. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataAuthenticationOptions.class, - visible = true) -@JsonTypeName("OnYourDataAuthenticationOptions") -@JsonSubTypes({ - @JsonSubTypes.Type(name = "api_key", value = OnYourDataApiKeyAuthenticationOptions.class), - @JsonSubTypes.Type(name = "connection_string", value = OnYourDataConnectionStringAuthenticationOptions.class), - @JsonSubTypes.Type(name = "key_and_key_id", value = OnYourDataKeyAndKeyIdAuthenticationOptions.class), - @JsonSubTypes.Type(name = "encoded_api_key", value = OnYourDataEncodedApiKeyAuthenticationOptions.class), - @JsonSubTypes.Type(name = "access_token", value = OnYourDataAccessTokenAuthenticationOptions.class), - @JsonSubTypes.Type( - name = "system_assigned_managed_identity", - value = OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.class), - @JsonSubTypes.Type( - name = "user_assigned_managed_identity", - value = OnYourDataUserAssignedManagedIdentityAuthenticationOptions.class) }) @Immutable -public class OnYourDataAuthenticationOptions { +public class OnYourDataAuthenticationOptions implements JsonSerializable { /** * Creates an instance of OnYourDataAuthenticationOptions class. @@ -47,8 +29,6 @@ public OnYourDataAuthenticationOptions() { * The authentication type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataAuthenticationType type; /** @@ -60,4 +40,81 @@ public OnYourDataAuthenticationOptions() { public OnYourDataAuthenticationType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataAuthenticationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataAuthenticationOptions if the JsonReader was pointing to an instance of it, or + * null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the OnYourDataAuthenticationOptions. + */ + @Generated + public static OnYourDataAuthenticationOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("api_key".equals(discriminatorValue)) { + return OnYourDataApiKeyAuthenticationOptions.fromJson(readerToUse.reset()); + } else if ("connection_string".equals(discriminatorValue)) { + return OnYourDataConnectionStringAuthenticationOptions.fromJson(readerToUse.reset()); + } else if ("key_and_key_id".equals(discriminatorValue)) { + return OnYourDataKeyAndKeyIdAuthenticationOptions.fromJson(readerToUse.reset()); + } else if ("encoded_api_key".equals(discriminatorValue)) { + return OnYourDataEncodedApiKeyAuthenticationOptions.fromJson(readerToUse.reset()); + } else if ("access_token".equals(discriminatorValue)) { + return OnYourDataAccessTokenAuthenticationOptions.fromJson(readerToUse.reset()); + } else if ("system_assigned_managed_identity".equals(discriminatorValue)) { + return OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.fromJson(readerToUse.reset()); + } else if ("user_assigned_managed_identity".equals(discriminatorValue)) { + return OnYourDataUserAssignedManagedIdentityAuthenticationOptions.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static OnYourDataAuthenticationOptions fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OnYourDataAuthenticationOptions deserializedOnYourDataAuthenticationOptions + = new OnYourDataAuthenticationOptions(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedOnYourDataAuthenticationOptions.type + = OnYourDataAuthenticationType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedOnYourDataAuthenticationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAuthenticationType.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAuthenticationType.java index 764f11885e9e7..83dbc42141f0b 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAuthenticationType.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataAuthenticationType.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -74,7 +73,6 @@ public OnYourDataAuthenticationType() { * @return the corresponding OnYourDataAuthenticationType. */ @Generated - @JsonCreator public static OnYourDataAuthenticationType fromString(String name) { return fromString(name, OnYourDataAuthenticationType.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataConnectionStringAuthenticationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataConnectionStringAuthenticationOptions.java index c550ca8f6c967..4cc8431993dbb 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataConnectionStringAuthenticationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataConnectionStringAuthenticationOptions.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The authentication options for Azure OpenAI On Your Data when using a connection string. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataConnectionStringAuthenticationOptions.class, - visible = true) -@JsonTypeName("connection_string") @Immutable public final class OnYourDataConnectionStringAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -27,7 +20,6 @@ public final class OnYourDataConnectionStringAuthenticationOptions extends OnYou * The connection string to use for authentication. */ @Generated - @JsonProperty(value = "connection_string") private final String connectionString; /** @@ -36,9 +28,7 @@ public final class OnYourDataConnectionStringAuthenticationOptions extends OnYou * @param connectionString the connectionString value to set. */ @Generated - @JsonCreator - public OnYourDataConnectionStringAuthenticationOptions( - @JsonProperty(value = "connection_string") String connectionString) { + public OnYourDataConnectionStringAuthenticationOptions(String connectionString) { this.connectionString = connectionString; } @@ -56,8 +46,6 @@ public String getConnectionString() { * The authentication type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataAuthenticationType type = OnYourDataAuthenticationType.CONNECTION_STRING; /** @@ -70,4 +58,48 @@ public String getConnectionString() { public OnYourDataAuthenticationType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("connection_string", this.connectionString); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataConnectionStringAuthenticationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataConnectionStringAuthenticationOptions 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 OnYourDataConnectionStringAuthenticationOptions. + */ + @Generated + public static OnYourDataConnectionStringAuthenticationOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String connectionString = null; + OnYourDataAuthenticationType type = OnYourDataAuthenticationType.CONNECTION_STRING; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("connection_string".equals(fieldName)) { + connectionString = reader.getString(); + } else if ("type".equals(fieldName)) { + type = OnYourDataAuthenticationType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + OnYourDataConnectionStringAuthenticationOptions deserializedOnYourDataConnectionStringAuthenticationOptions + = new OnYourDataConnectionStringAuthenticationOptions(connectionString); + deserializedOnYourDataConnectionStringAuthenticationOptions.type = type; + return deserializedOnYourDataConnectionStringAuthenticationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataDeploymentNameVectorizationSource.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataDeploymentNameVectorizationSource.java index d3115802bb433..1dec9a998e923 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataDeploymentNameVectorizationSource.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataDeploymentNameVectorizationSource.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based * on an internal embeddings model deployment name in the same Azure OpenAI resource. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataDeploymentNameVectorizationSource.class, - visible = true) -@JsonTypeName("deployment_name") @Immutable public final class OnYourDataDeploymentNameVectorizationSource extends OnYourDataVectorizationSource { @@ -28,7 +21,6 @@ public final class OnYourDataDeploymentNameVectorizationSource extends OnYourDat * The embedding model deployment name within the same Azure OpenAI resource. This enables you to use vector search without Azure OpenAI api-key and without Azure OpenAI public network access. */ @Generated - @JsonProperty(value = "deployment_name") private final String deploymentName; /** @@ -37,8 +29,7 @@ public final class OnYourDataDeploymentNameVectorizationSource extends OnYourDat * @param deploymentName the deploymentName value to set. */ @Generated - @JsonCreator - public OnYourDataDeploymentNameVectorizationSource(@JsonProperty(value = "deployment_name") String deploymentName) { + public OnYourDataDeploymentNameVectorizationSource(String deploymentName) { this.deploymentName = deploymentName; } @@ -57,8 +48,6 @@ public String getDeploymentName() { * The type of vectorization source to use. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataVectorizationSourceType type = OnYourDataVectorizationSourceType.DEPLOYMENT_NAME; /** @@ -71,4 +60,48 @@ public String getDeploymentName() { public OnYourDataVectorizationSourceType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("deployment_name", this.deploymentName); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataDeploymentNameVectorizationSource from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataDeploymentNameVectorizationSource 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 OnYourDataDeploymentNameVectorizationSource. + */ + @Generated + public static OnYourDataDeploymentNameVectorizationSource fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String deploymentName = null; + OnYourDataVectorizationSourceType type = OnYourDataVectorizationSourceType.DEPLOYMENT_NAME; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("deployment_name".equals(fieldName)) { + deploymentName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = OnYourDataVectorizationSourceType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + OnYourDataDeploymentNameVectorizationSource deserializedOnYourDataDeploymentNameVectorizationSource + = new OnYourDataDeploymentNameVectorizationSource(deploymentName); + deserializedOnYourDataDeploymentNameVectorizationSource.type = type; + return deserializedOnYourDataDeploymentNameVectorizationSource; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataEncodedApiKeyAuthenticationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataEncodedApiKeyAuthenticationOptions.java index 2ec4920a2aeed..7216d225ec744 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataEncodedApiKeyAuthenticationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataEncodedApiKeyAuthenticationOptions.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The authentication options for Azure OpenAI On Your Data when using an Elasticsearch encoded API key. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataEncodedApiKeyAuthenticationOptions.class, - visible = true) -@JsonTypeName("encoded_api_key") @Immutable public final class OnYourDataEncodedApiKeyAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -27,7 +20,6 @@ public final class OnYourDataEncodedApiKeyAuthenticationOptions extends OnYourDa * The encoded API key to use for authentication. */ @Generated - @JsonProperty(value = "encoded_api_key") private final String encodedApiKey; /** @@ -36,8 +28,7 @@ public final class OnYourDataEncodedApiKeyAuthenticationOptions extends OnYourDa * @param encodedApiKey the encodedApiKey value to set. */ @Generated - @JsonCreator - public OnYourDataEncodedApiKeyAuthenticationOptions(@JsonProperty(value = "encoded_api_key") String encodedApiKey) { + public OnYourDataEncodedApiKeyAuthenticationOptions(String encodedApiKey) { this.encodedApiKey = encodedApiKey; } @@ -55,8 +46,6 @@ public String getEncodedApiKey() { * The authentication type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataAuthenticationType type = OnYourDataAuthenticationType.ENCODED_API_KEY; /** @@ -69,4 +58,48 @@ public String getEncodedApiKey() { public OnYourDataAuthenticationType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("encoded_api_key", this.encodedApiKey); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataEncodedApiKeyAuthenticationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataEncodedApiKeyAuthenticationOptions 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 OnYourDataEncodedApiKeyAuthenticationOptions. + */ + @Generated + public static OnYourDataEncodedApiKeyAuthenticationOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String encodedApiKey = null; + OnYourDataAuthenticationType type = OnYourDataAuthenticationType.ENCODED_API_KEY; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("encoded_api_key".equals(fieldName)) { + encodedApiKey = reader.getString(); + } else if ("type".equals(fieldName)) { + type = OnYourDataAuthenticationType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + OnYourDataEncodedApiKeyAuthenticationOptions deserializedOnYourDataEncodedApiKeyAuthenticationOptions + = new OnYourDataEncodedApiKeyAuthenticationOptions(encodedApiKey); + deserializedOnYourDataEncodedApiKeyAuthenticationOptions.type = type; + return deserializedOnYourDataEncodedApiKeyAuthenticationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataEndpointVectorizationSource.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataEndpointVectorizationSource.java index 063e5e6f21f67..55d40ca8fc38b 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataEndpointVectorizationSource.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataEndpointVectorizationSource.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based * on a public Azure OpenAI endpoint call for embeddings. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataEndpointVectorizationSource.class, - visible = true) -@JsonTypeName("endpoint") @Immutable public final class OnYourDataEndpointVectorizationSource extends OnYourDataVectorizationSource { @@ -28,14 +21,12 @@ public final class OnYourDataEndpointVectorizationSource extends OnYourDataVecto * Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. */ @Generated - @JsonProperty(value = "endpoint") private final String endpoint; /* * Specifies the authentication options to use when retrieving embeddings from the specified endpoint. */ @Generated - @JsonProperty(value = "authentication") private final OnYourDataAuthenticationOptions authentication; /** @@ -45,9 +36,7 @@ public final class OnYourDataEndpointVectorizationSource extends OnYourDataVecto * @param authentication the authentication value to set. */ @Generated - @JsonCreator - public OnYourDataEndpointVectorizationSource(@JsonProperty(value = "endpoint") String endpoint, - @JsonProperty(value = "authentication") OnYourDataAuthenticationOptions authentication) { + public OnYourDataEndpointVectorizationSource(String endpoint, OnYourDataAuthenticationOptions authentication) { this.endpoint = endpoint; this.authentication = authentication; } @@ -80,8 +69,6 @@ public OnYourDataAuthenticationOptions getAuthentication() { * The type of vectorization source to use. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataVectorizationSourceType type = OnYourDataVectorizationSourceType.ENDPOINT; /** @@ -94,4 +81,52 @@ public OnYourDataAuthenticationOptions getAuthentication() { public OnYourDataVectorizationSourceType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("endpoint", this.endpoint); + jsonWriter.writeJsonField("authentication", this.authentication); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataEndpointVectorizationSource from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataEndpointVectorizationSource 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 OnYourDataEndpointVectorizationSource. + */ + @Generated + public static OnYourDataEndpointVectorizationSource fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String endpoint = null; + OnYourDataAuthenticationOptions authentication = null; + OnYourDataVectorizationSourceType type = OnYourDataVectorizationSourceType.ENDPOINT; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("endpoint".equals(fieldName)) { + endpoint = reader.getString(); + } else if ("authentication".equals(fieldName)) { + authentication = OnYourDataAuthenticationOptions.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = OnYourDataVectorizationSourceType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + OnYourDataEndpointVectorizationSource deserializedOnYourDataEndpointVectorizationSource + = new OnYourDataEndpointVectorizationSource(endpoint, authentication); + deserializedOnYourDataEndpointVectorizationSource.type = type; + return deserializedOnYourDataEndpointVectorizationSource; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataKeyAndKeyIdAuthenticationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataKeyAndKeyIdAuthenticationOptions.java index 484f16b6abdfa..f02a0ae82ba6b 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataKeyAndKeyIdAuthenticationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataKeyAndKeyIdAuthenticationOptions.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The authentication options for Azure OpenAI On Your Data when using an Elasticsearch key and key ID pair. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataKeyAndKeyIdAuthenticationOptions.class, - visible = true) -@JsonTypeName("key_and_key_id") @Immutable public final class OnYourDataKeyAndKeyIdAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -27,14 +20,12 @@ public final class OnYourDataKeyAndKeyIdAuthenticationOptions extends OnYourData * The key to use for authentication. */ @Generated - @JsonProperty(value = "key") private final String key; /* * The key ID to use for authentication. */ @Generated - @JsonProperty(value = "key_id") private final String keyId; /** @@ -44,9 +35,7 @@ public final class OnYourDataKeyAndKeyIdAuthenticationOptions extends OnYourData * @param keyId the keyId value to set. */ @Generated - @JsonCreator - public OnYourDataKeyAndKeyIdAuthenticationOptions(@JsonProperty(value = "key") String key, - @JsonProperty(value = "key_id") String keyId) { + public OnYourDataKeyAndKeyIdAuthenticationOptions(String key, String keyId) { this.key = key; this.keyId = keyId; } @@ -75,8 +64,6 @@ public String getKeyId() { * The authentication type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataAuthenticationType type = OnYourDataAuthenticationType.KEY_AND_KEY_ID; /** @@ -89,4 +76,52 @@ public String getKeyId() { public OnYourDataAuthenticationType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("key", this.key); + jsonWriter.writeStringField("key_id", this.keyId); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataKeyAndKeyIdAuthenticationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataKeyAndKeyIdAuthenticationOptions 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 OnYourDataKeyAndKeyIdAuthenticationOptions. + */ + @Generated + public static OnYourDataKeyAndKeyIdAuthenticationOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String key = null; + String keyId = null; + OnYourDataAuthenticationType type = OnYourDataAuthenticationType.KEY_AND_KEY_ID; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("key".equals(fieldName)) { + key = reader.getString(); + } else if ("key_id".equals(fieldName)) { + keyId = reader.getString(); + } else if ("type".equals(fieldName)) { + type = OnYourDataAuthenticationType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + OnYourDataKeyAndKeyIdAuthenticationOptions deserializedOnYourDataKeyAndKeyIdAuthenticationOptions + = new OnYourDataKeyAndKeyIdAuthenticationOptions(key, keyId); + deserializedOnYourDataKeyAndKeyIdAuthenticationOptions.type = type; + return deserializedOnYourDataKeyAndKeyIdAuthenticationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataModelIdVectorizationSource.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataModelIdVectorizationSource.java index 0701a9ea39ba3..b8d24687bf0d2 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataModelIdVectorizationSource.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataModelIdVectorizationSource.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based * on a search service model ID. Currently only supported by Elasticsearch®. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataModelIdVectorizationSource.class, - visible = true) -@JsonTypeName("model_id") @Immutable public final class OnYourDataModelIdVectorizationSource extends OnYourDataVectorizationSource { @@ -28,7 +21,6 @@ public final class OnYourDataModelIdVectorizationSource extends OnYourDataVector * The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. */ @Generated - @JsonProperty(value = "model_id") private final String modelId; /** @@ -37,8 +29,7 @@ public final class OnYourDataModelIdVectorizationSource extends OnYourDataVector * @param modelId the modelId value to set. */ @Generated - @JsonCreator - public OnYourDataModelIdVectorizationSource(@JsonProperty(value = "model_id") String modelId) { + public OnYourDataModelIdVectorizationSource(String modelId) { this.modelId = modelId; } @@ -57,8 +48,6 @@ public String getModelId() { * The type of vectorization source to use. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataVectorizationSourceType type = OnYourDataVectorizationSourceType.MODEL_ID; /** @@ -71,4 +60,48 @@ public String getModelId() { public OnYourDataVectorizationSourceType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("model_id", this.modelId); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataModelIdVectorizationSource from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataModelIdVectorizationSource 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 OnYourDataModelIdVectorizationSource. + */ + @Generated + public static OnYourDataModelIdVectorizationSource fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String modelId = null; + OnYourDataVectorizationSourceType type = OnYourDataVectorizationSourceType.MODEL_ID; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("model_id".equals(fieldName)) { + modelId = reader.getString(); + } else if ("type".equals(fieldName)) { + type = OnYourDataVectorizationSourceType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + OnYourDataModelIdVectorizationSource deserializedOnYourDataModelIdVectorizationSource + = new OnYourDataModelIdVectorizationSource(modelId); + deserializedOnYourDataModelIdVectorizationSource.type = type; + return deserializedOnYourDataModelIdVectorizationSource; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.java index 6083df3239789..50e392f7edf21 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.java @@ -5,20 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The authentication options for Azure OpenAI On Your Data when using a system-assigned managed identity. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.class, - visible = true) -@JsonTypeName("system_assigned_managed_identity") @Immutable public final class OnYourDataSystemAssignedManagedIdentityAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -34,8 +28,6 @@ public OnYourDataSystemAssignedManagedIdentityAuthenticationOptions() { * The authentication type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataAuthenticationType type = OnYourDataAuthenticationType.SYSTEM_ASSIGNED_MANAGED_IDENTITY; /** @@ -48,4 +40,44 @@ public OnYourDataSystemAssignedManagedIdentityAuthenticationOptions() { public OnYourDataAuthenticationType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataSystemAssignedManagedIdentityAuthenticationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataSystemAssignedManagedIdentityAuthenticationOptions if the JsonReader was + * pointing to an instance of it, or null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the + * OnYourDataSystemAssignedManagedIdentityAuthenticationOptions. + */ + @Generated + public static OnYourDataSystemAssignedManagedIdentityAuthenticationOptions fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + OnYourDataSystemAssignedManagedIdentityAuthenticationOptions deserializedOnYourDataSystemAssignedManagedIdentityAuthenticationOptions + = new OnYourDataSystemAssignedManagedIdentityAuthenticationOptions(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedOnYourDataSystemAssignedManagedIdentityAuthenticationOptions.type + = OnYourDataAuthenticationType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedOnYourDataSystemAssignedManagedIdentityAuthenticationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.java index b19b95d72b562..424cd1db41245 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.java @@ -5,21 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * The authentication options for Azure OpenAI On Your Data when using a user-assigned managed identity. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataUserAssignedManagedIdentityAuthenticationOptions.class, - visible = true) -@JsonTypeName("user_assigned_managed_identity") @Immutable public final class OnYourDataUserAssignedManagedIdentityAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -27,7 +20,6 @@ public final class OnYourDataUserAssignedManagedIdentityAuthenticationOptions ex * The resource ID of the user-assigned managed identity to use for authentication. */ @Generated - @JsonProperty(value = "managed_identity_resource_id") private final String managedIdentityResourceId; /** @@ -36,9 +28,7 @@ public final class OnYourDataUserAssignedManagedIdentityAuthenticationOptions ex * @param managedIdentityResourceId the managedIdentityResourceId value to set. */ @Generated - @JsonCreator - public OnYourDataUserAssignedManagedIdentityAuthenticationOptions( - @JsonProperty(value = "managed_identity_resource_id") String managedIdentityResourceId) { + public OnYourDataUserAssignedManagedIdentityAuthenticationOptions(String managedIdentityResourceId) { this.managedIdentityResourceId = managedIdentityResourceId; } @@ -57,8 +47,6 @@ public String getManagedIdentityResourceId() { * The authentication type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataAuthenticationType type = OnYourDataAuthenticationType.USER_ASSIGNED_MANAGED_IDENTITY; /** @@ -71,4 +59,50 @@ public String getManagedIdentityResourceId() { public OnYourDataAuthenticationType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("managed_identity_resource_id", this.managedIdentityResourceId); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataUserAssignedManagedIdentityAuthenticationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataUserAssignedManagedIdentityAuthenticationOptions 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 + * OnYourDataUserAssignedManagedIdentityAuthenticationOptions. + */ + @Generated + public static OnYourDataUserAssignedManagedIdentityAuthenticationOptions fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + String managedIdentityResourceId = null; + OnYourDataAuthenticationType type = OnYourDataAuthenticationType.USER_ASSIGNED_MANAGED_IDENTITY; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("managed_identity_resource_id".equals(fieldName)) { + managedIdentityResourceId = reader.getString(); + } else if ("type".equals(fieldName)) { + type = OnYourDataAuthenticationType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + OnYourDataUserAssignedManagedIdentityAuthenticationOptions deserializedOnYourDataUserAssignedManagedIdentityAuthenticationOptions + = new OnYourDataUserAssignedManagedIdentityAuthenticationOptions(managedIdentityResourceId); + deserializedOnYourDataUserAssignedManagedIdentityAuthenticationOptions.type = type; + return deserializedOnYourDataUserAssignedManagedIdentityAuthenticationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataVectorizationSource.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataVectorizationSource.java index ae0b7afc80816..41b1ca9b7e0f7 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataVectorizationSource.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataVectorizationSource.java @@ -5,27 +5,17 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * An abstract representation of a vectorization source for Azure OpenAI On Your Data with vector search. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = OnYourDataVectorizationSource.class, - visible = true) -@JsonTypeName("OnYourDataVectorizationSource") -@JsonSubTypes({ - @JsonSubTypes.Type(name = "endpoint", value = OnYourDataEndpointVectorizationSource.class), - @JsonSubTypes.Type(name = "deployment_name", value = OnYourDataDeploymentNameVectorizationSource.class), - @JsonSubTypes.Type(name = "model_id", value = OnYourDataModelIdVectorizationSource.class) }) @Immutable -public class OnYourDataVectorizationSource { +public class OnYourDataVectorizationSource implements JsonSerializable { /** * Creates an instance of OnYourDataVectorizationSource class. @@ -39,8 +29,6 @@ public OnYourDataVectorizationSource() { * The type of vectorization source to use. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private OnYourDataVectorizationSourceType type; /** @@ -52,4 +40,73 @@ public OnYourDataVectorizationSource() { public OnYourDataVectorizationSourceType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OnYourDataVectorizationSource from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OnYourDataVectorizationSource if the JsonReader was pointing to an instance of it, or null + * if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the OnYourDataVectorizationSource. + */ + @Generated + public static OnYourDataVectorizationSource fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("endpoint".equals(discriminatorValue)) { + return OnYourDataEndpointVectorizationSource.fromJson(readerToUse.reset()); + } else if ("deployment_name".equals(discriminatorValue)) { + return OnYourDataDeploymentNameVectorizationSource.fromJson(readerToUse.reset()); + } else if ("model_id".equals(discriminatorValue)) { + return OnYourDataModelIdVectorizationSource.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static OnYourDataVectorizationSource fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OnYourDataVectorizationSource deserializedOnYourDataVectorizationSource + = new OnYourDataVectorizationSource(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedOnYourDataVectorizationSource.type + = OnYourDataVectorizationSourceType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedOnYourDataVectorizationSource; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataVectorizationSourceType.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataVectorizationSourceType.java index 5932b0a5b8764..5f10b076964c9 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataVectorizationSourceType.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OnYourDataVectorizationSourceType.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -53,7 +52,6 @@ public OnYourDataVectorizationSourceType() { * @return the corresponding OnYourDataVectorizationSourceType. */ @Generated - @JsonCreator public static OnYourDataVectorizationSourceType fromString(String name) { return fromString(name, OnYourDataVectorizationSourceType.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeChatExtensionConfiguration.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeChatExtensionConfiguration.java index 54d9e022c0404..d94269301d507 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeChatExtensionConfiguration.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeChatExtensionConfiguration.java @@ -5,22 +5,15 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A specific representation of configurable options for Pinecone when using it as an Azure OpenAI chat * extension. */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - defaultImpl = PineconeChatExtensionConfiguration.class, - visible = true) -@JsonTypeName("pinecone") @Immutable public final class PineconeChatExtensionConfiguration extends AzureChatExtensionConfiguration { @@ -28,7 +21,6 @@ public final class PineconeChatExtensionConfiguration extends AzureChatExtension * The parameters to use when configuring Azure OpenAI chat extensions. */ @Generated - @JsonProperty(value = "parameters") private final PineconeChatExtensionParameters parameters; /** @@ -47,9 +39,7 @@ public PineconeChatExtensionParameters getParameters() { * @param parameters the parameters value to set. */ @Generated - @JsonCreator - public PineconeChatExtensionConfiguration( - @JsonProperty(value = "parameters") PineconeChatExtensionParameters parameters) { + public PineconeChatExtensionConfiguration(PineconeChatExtensionParameters parameters) { this.parameters = parameters; } @@ -58,8 +48,6 @@ public PineconeChatExtensionConfiguration( * Azure chat extensions are only compatible with Azure OpenAI. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private AzureChatExtensionType type = AzureChatExtensionType.PINECONE; /** @@ -74,4 +62,48 @@ public PineconeChatExtensionConfiguration( public AzureChatExtensionType getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("parameters", this.parameters); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PineconeChatExtensionConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PineconeChatExtensionConfiguration 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 PineconeChatExtensionConfiguration. + */ + @Generated + public static PineconeChatExtensionConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PineconeChatExtensionParameters parameters = null; + AzureChatExtensionType type = AzureChatExtensionType.PINECONE; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("parameters".equals(fieldName)) { + parameters = PineconeChatExtensionParameters.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = AzureChatExtensionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + PineconeChatExtensionConfiguration deserializedPineconeChatExtensionConfiguration + = new PineconeChatExtensionConfiguration(parameters); + deserializedPineconeChatExtensionConfiguration.type = type; + return deserializedPineconeChatExtensionConfiguration; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeChatExtensionParameters.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeChatExtensionParameters.java index c3f451fadfa3a..fcabc46f0198e 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeChatExtensionParameters.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeChatExtensionParameters.java @@ -5,14 +5,17 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * Parameters for configuring Azure OpenAI Pinecone chat extensions. The supported authentication type is APIKey. */ @Fluent -public final class PineconeChatExtensionParameters { +public final class PineconeChatExtensionParameters implements JsonSerializable { /* * The authentication method to use when accessing the defined data source. @@ -22,63 +25,54 @@ public final class PineconeChatExtensionParameters { * authentication. */ @Generated - @JsonProperty(value = "authentication") private OnYourDataAuthenticationOptions authentication; /* * The configured top number of documents to feature for the configured query. */ @Generated - @JsonProperty(value = "top_n_documents") private Integer topNDocuments; /* * Whether queries should be restricted to use of indexed data. */ @Generated - @JsonProperty(value = "in_scope") private Boolean inScope; /* * The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ @Generated - @JsonProperty(value = "strictness") private Integer strictness; /* * Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ @Generated - @JsonProperty(value = "role_information") private String roleInformation; /* * The environment name of Pinecone. */ @Generated - @JsonProperty(value = "environment") private final String environment; /* * The name of the Pinecone database index. */ @Generated - @JsonProperty(value = "index_name") private final String indexName; /* * Customized field mapping behavior to use when interacting with the search index. */ @Generated - @JsonProperty(value = "fields_mapping") private final PineconeFieldMappingOptions fieldsMapping; /* * The embedding dependency for vector search. */ @Generated - @JsonProperty(value = "embedding_dependency") private final OnYourDataVectorizationSource embeddingDependency; /** @@ -256,14 +250,87 @@ public OnYourDataVectorizationSource getEmbeddingDependency() { * @param embeddingDependency the embeddingDependency value to set. */ @Generated - @JsonCreator - public PineconeChatExtensionParameters(@JsonProperty(value = "environment") String environment, - @JsonProperty(value = "index_name") String indexName, - @JsonProperty(value = "fields_mapping") PineconeFieldMappingOptions fieldsMapping, - @JsonProperty(value = "embedding_dependency") OnYourDataVectorizationSource embeddingDependency) { + public PineconeChatExtensionParameters(String environment, String indexName, + PineconeFieldMappingOptions fieldsMapping, OnYourDataVectorizationSource embeddingDependency) { this.environment = environment; this.indexName = indexName; this.fieldsMapping = fieldsMapping; this.embeddingDependency = embeddingDependency; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("environment", this.environment); + jsonWriter.writeStringField("index_name", this.indexName); + jsonWriter.writeJsonField("fields_mapping", this.fieldsMapping); + jsonWriter.writeJsonField("embedding_dependency", this.embeddingDependency); + jsonWriter.writeJsonField("authentication", this.authentication); + jsonWriter.writeNumberField("top_n_documents", this.topNDocuments); + jsonWriter.writeBooleanField("in_scope", this.inScope); + jsonWriter.writeNumberField("strictness", this.strictness); + jsonWriter.writeStringField("role_information", this.roleInformation); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PineconeChatExtensionParameters from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PineconeChatExtensionParameters 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 PineconeChatExtensionParameters. + */ + @Generated + public static PineconeChatExtensionParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String environment = null; + String indexName = null; + PineconeFieldMappingOptions fieldsMapping = null; + OnYourDataVectorizationSource embeddingDependency = null; + OnYourDataAuthenticationOptions authentication = null; + Integer topNDocuments = null; + Boolean inScope = null; + Integer strictness = null; + String roleInformation = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("environment".equals(fieldName)) { + environment = reader.getString(); + } else if ("index_name".equals(fieldName)) { + indexName = reader.getString(); + } else if ("fields_mapping".equals(fieldName)) { + fieldsMapping = PineconeFieldMappingOptions.fromJson(reader); + } else if ("embedding_dependency".equals(fieldName)) { + embeddingDependency = OnYourDataVectorizationSource.fromJson(reader); + } else if ("authentication".equals(fieldName)) { + authentication = OnYourDataAuthenticationOptions.fromJson(reader); + } else if ("top_n_documents".equals(fieldName)) { + topNDocuments = reader.getNullable(JsonReader::getInt); + } else if ("in_scope".equals(fieldName)) { + inScope = reader.getNullable(JsonReader::getBoolean); + } else if ("strictness".equals(fieldName)) { + strictness = reader.getNullable(JsonReader::getInt); + } else if ("role_information".equals(fieldName)) { + roleInformation = reader.getString(); + } else { + reader.skipChildren(); + } + } + PineconeChatExtensionParameters deserializedPineconeChatExtensionParameters + = new PineconeChatExtensionParameters(environment, indexName, fieldsMapping, embeddingDependency); + deserializedPineconeChatExtensionParameters.authentication = authentication; + deserializedPineconeChatExtensionParameters.topNDocuments = topNDocuments; + deserializedPineconeChatExtensionParameters.inScope = inScope; + deserializedPineconeChatExtensionParameters.strictness = strictness; + deserializedPineconeChatExtensionParameters.roleInformation = roleInformation; + return deserializedPineconeChatExtensionParameters; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeFieldMappingOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeFieldMappingOptions.java index 92c74c1be7e8e..fe9c34b3ae75f 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeFieldMappingOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PineconeFieldMappingOptions.java @@ -5,49 +5,47 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; import java.util.List; /** * Optional settings to control how fields are processed when using a configured Pinecone resource. */ @Fluent -public final class PineconeFieldMappingOptions { +public final class PineconeFieldMappingOptions implements JsonSerializable { /* * The name of the index field to use as a title. */ @Generated - @JsonProperty(value = "title_field") private String titleField; /* * The name of the index field to use as a URL. */ @Generated - @JsonProperty(value = "url_field") private String urlField; /* * The name of the index field to use as a filepath. */ @Generated - @JsonProperty(value = "filepath_field") private String filepathField; /* * The names of index fields that should be treated as content. */ @Generated - @JsonProperty(value = "content_fields") private final List contentFields; /* * The separator pattern that content fields should use. */ @Generated - @JsonProperty(value = "content_fields_separator") private String contentFieldsSeparator; /** @@ -154,8 +152,67 @@ public PineconeFieldMappingOptions setContentFieldsSeparator(String contentField * @param contentFields the contentFields value to set. */ @Generated - @JsonCreator - public PineconeFieldMappingOptions(@JsonProperty(value = "content_fields") List contentFields) { + public PineconeFieldMappingOptions(List contentFields) { this.contentFields = contentFields; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("content_fields", this.contentFields, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("title_field", this.titleField); + jsonWriter.writeStringField("url_field", this.urlField); + jsonWriter.writeStringField("filepath_field", this.filepathField); + jsonWriter.writeStringField("content_fields_separator", this.contentFieldsSeparator); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PineconeFieldMappingOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PineconeFieldMappingOptions 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 PineconeFieldMappingOptions. + */ + @Generated + public static PineconeFieldMappingOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List contentFields = null; + String titleField = null; + String urlField = null; + String filepathField = null; + String contentFieldsSeparator = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("content_fields".equals(fieldName)) { + contentFields = reader.readArray(reader1 -> reader1.getString()); + } else if ("title_field".equals(fieldName)) { + titleField = reader.getString(); + } else if ("url_field".equals(fieldName)) { + urlField = reader.getString(); + } else if ("filepath_field".equals(fieldName)) { + filepathField = reader.getString(); + } else if ("content_fields_separator".equals(fieldName)) { + contentFieldsSeparator = reader.getString(); + } else { + reader.skipChildren(); + } + } + PineconeFieldMappingOptions deserializedPineconeFieldMappingOptions + = new PineconeFieldMappingOptions(contentFields); + deserializedPineconeFieldMappingOptions.titleField = titleField; + deserializedPineconeFieldMappingOptions.urlField = urlField; + deserializedPineconeFieldMappingOptions.filepathField = filepathField; + deserializedPineconeFieldMappingOptions.contentFieldsSeparator = contentFieldsSeparator; + return deserializedPineconeFieldMappingOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechGenerationOptions.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechGenerationOptions.java index a47a809015484..4dd15424ee2b6 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechGenerationOptions.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechGenerationOptions.java @@ -5,41 +5,40 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A representation of the request options that control the behavior of a text-to-speech operation. */ @Fluent -public final class SpeechGenerationOptions { +public final class SpeechGenerationOptions implements JsonSerializable { /* * The text to generate audio for. The maximum length is 4096 characters. */ @Generated - @JsonProperty(value = "input") private final String input; /* * The voice to use for text-to-speech. */ @Generated - @JsonProperty(value = "voice") private final SpeechVoice voice; /* * The audio output format for the spoken text. By default, the MP3 format will be used. */ @Generated - @JsonProperty(value = "response_format") private SpeechGenerationResponseFormat responseFormat; /* * The speed of speech for generated audio. Values are valid in the range from 0.25 to 4.0, with 1.0 the default and higher values corresponding to faster speech. */ @Generated - @JsonProperty(value = "speed") private Double speed; /** @@ -49,9 +48,7 @@ public final class SpeechGenerationOptions { * @param voice the voice value to set. */ @Generated - @JsonCreator - public SpeechGenerationOptions(@JsonProperty(value = "input") String input, - @JsonProperty(value = "voice") SpeechVoice voice) { + public SpeechGenerationOptions(String input, SpeechVoice voice) { this.input = input; this.voice = voice; } @@ -128,7 +125,6 @@ public SpeechGenerationOptions setSpeed(Double speed) { * The model to use for this text-to-speech request. */ @Generated - @JsonProperty(value = "model") private String model; /** @@ -152,4 +148,62 @@ public SpeechGenerationOptions setModel(String model) { this.model = model; return this; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("input", this.input); + jsonWriter.writeStringField("voice", this.voice == null ? null : this.voice.toString()); + jsonWriter.writeStringField("response_format", + this.responseFormat == null ? null : this.responseFormat.toString()); + jsonWriter.writeNumberField("speed", this.speed); + jsonWriter.writeStringField("model", this.model); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SpeechGenerationOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SpeechGenerationOptions 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 SpeechGenerationOptions. + */ + @Generated + public static SpeechGenerationOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String input = null; + SpeechVoice voice = null; + SpeechGenerationResponseFormat responseFormat = null; + Double speed = null; + String model = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("input".equals(fieldName)) { + input = reader.getString(); + } else if ("voice".equals(fieldName)) { + voice = SpeechVoice.fromString(reader.getString()); + } else if ("response_format".equals(fieldName)) { + responseFormat = SpeechGenerationResponseFormat.fromString(reader.getString()); + } else if ("speed".equals(fieldName)) { + speed = reader.getNullable(JsonReader::getDouble); + } else if ("model".equals(fieldName)) { + model = reader.getString(); + } else { + reader.skipChildren(); + } + } + SpeechGenerationOptions deserializedSpeechGenerationOptions = new SpeechGenerationOptions(input, voice); + deserializedSpeechGenerationOptions.responseFormat = responseFormat; + deserializedSpeechGenerationOptions.speed = speed; + deserializedSpeechGenerationOptions.model = model; + return deserializedSpeechGenerationOptions; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechGenerationResponseFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechGenerationResponseFormat.java index ea4c86f2b8e3b..b1febad4c76cf 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechGenerationResponseFormat.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechGenerationResponseFormat.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -56,7 +55,6 @@ public SpeechGenerationResponseFormat() { * @return the corresponding SpeechGenerationResponseFormat. */ @Generated - @JsonCreator public static SpeechGenerationResponseFormat fromString(String name) { return fromString(name, SpeechGenerationResponseFormat.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechVoice.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechVoice.java index 0b012e201c84e..253bfb13c41ec 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechVoice.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/SpeechVoice.java @@ -5,7 +5,6 @@ import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; -import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** @@ -66,7 +65,6 @@ public SpeechVoice() { * @return the corresponding SpeechVoice. */ @Generated - @JsonCreator public static SpeechVoice fromString(String name) { return fromString(name, SpeechVoice.class); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/StopFinishDetails.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/StopFinishDetails.java index 3894c6c9e3ba9..b768d4839c5e7 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/StopFinishDetails.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/StopFinishDetails.java @@ -5,17 +5,14 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeId; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; /** * A structured representation of a stop reason that signifies natural termination by the model. */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = StopFinishDetails.class, visible = true) -@JsonTypeName("stop") @Immutable public final class StopFinishDetails extends ChatFinishDetails { @@ -23,7 +20,6 @@ public final class StopFinishDetails extends ChatFinishDetails { * The token sequence that the model terminated with. */ @Generated - @JsonProperty(value = "stop") private final String stop; /** @@ -32,8 +28,7 @@ public final class StopFinishDetails extends ChatFinishDetails { * @param stop the stop value to set. */ @Generated - @JsonCreator - private StopFinishDetails(@JsonProperty(value = "stop") String stop) { + private StopFinishDetails(String stop) { this.stop = stop; } @@ -51,8 +46,6 @@ public String getStop() { * The object type. */ @Generated - @JsonTypeId - @JsonProperty(value = "type") private String type = "stop"; /** @@ -65,4 +58,47 @@ public String getStop() { public String getType() { return this.type; } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("stop", this.stop); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StopFinishDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StopFinishDetails 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 StopFinishDetails. + */ + @Generated + public static StopFinishDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String stop = null; + String type = "stop"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("stop".equals(fieldName)) { + stop = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + StopFinishDetails deserializedStopFinishDetails = new StopFinishDetails(stop); + deserializedStopFinishDetails.type = type; + return deserializedStopFinishDetails; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/module-info.java b/sdk/openai/azure-ai-openai/src/main/java/module-info.java index 3df05ddde0b3b..0dc72ef67f53a 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/module-info.java +++ b/sdk/openai/azure-ai-openai/src/main/java/module-info.java @@ -4,9 +4,10 @@ module com.azure.ai.openai { requires transitive com.azure.core; + requires transitive com.azure.json; exports com.azure.ai.openai; exports com.azure.ai.openai.models; - opens com.azure.ai.openai.models to com.azure.core, com.fasterxml.jackson.databind; - opens com.azure.ai.openai.implementation.models to com.azure.core, com.fasterxml.jackson.databind; - opens com.azure.ai.openai.implementation to com.azure.core, com.fasterxml.jackson.databind; + opens com.azure.ai.openai.models to com.azure.core; + opens com.azure.ai.openai.implementation.models to com.azure.core; + opens com.azure.ai.openai.implementation to com.azure.core; } diff --git a/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/impl/ReadmeSamples.java b/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/impl/ReadmeSamples.java index 23b8adb106114..eedbbcc9be919 100644 --- a/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/impl/ReadmeSamples.java +++ b/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/impl/ReadmeSamples.java @@ -6,7 +6,7 @@ import com.azure.ai.openai.OpenAIAsyncClient; import com.azure.ai.openai.OpenAIClient; import com.azure.ai.openai.OpenAIClientBuilder; -import com.azure.ai.openai.functions.MyFunctionCallArguments; +import com.azure.ai.openai.MyFunctionCallArguments; import com.azure.ai.openai.models.AudioTranscription; import com.azure.ai.openai.models.AudioTranscriptionFormat; import com.azure.ai.openai.models.AudioTranscriptionOptions; diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/MyFunctionCallArguments.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/MyFunctionCallArguments.java new file mode 100644 index 0000000000000..3d71e08fe619d --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/MyFunctionCallArguments.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai; + +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; + +import java.io.IOException; + +public final class MyFunctionCallArguments implements JsonSerializable { + private String unit; + + private String location; + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public MyFunctionCallArguments() { + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("unit", this.unit); + jsonWriter.writeStringField("location", this.location); + return jsonWriter.writeEndObject(); + } + + public static MyFunctionCallArguments fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String unit = null; + String location = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("unit".equals(fieldName)) { + unit = reader.getString(); + } else if ("location".equals(fieldName)) { + location = reader.getString(); + } else { + reader.skipChildren(); + } + } + MyFunctionCallArguments model = new MyFunctionCallArguments(); + model.unit = unit; + model.location = location; + return model; + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/NonAzureOpenAIAsyncClientTest.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/NonAzureOpenAIAsyncClientTest.java index 3b739d25783b3..8373b7a1446d2 100644 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/NonAzureOpenAIAsyncClientTest.java +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/NonAzureOpenAIAsyncClientTest.java @@ -3,7 +3,6 @@ package com.azure.ai.openai; -import com.azure.ai.openai.functions.MyFunctionCallArguments; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscriptionFormat; import com.azure.ai.openai.models.AudioTranscriptionTimestampGranularity; @@ -303,7 +302,7 @@ public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersi chatChoice, "MyFunction", MyFunctionCallArguments.class); - assertEquals(arguments.getLocation(), "San Francisco, CA"); + assertTrue(arguments.getLocation().contains("San Francisco")); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); @@ -754,7 +753,6 @@ public void testGetChatCompletionsToolCall(HttpClient httpClient, OpenAIServiceV assertNotNull(responseMessage); assertTrue(responseMessage.getContent() == null || responseMessage.getContent().isEmpty()); assertFalse(responseMessage.getToolCalls() == null || responseMessage.getToolCalls().isEmpty()); - assertEquals(1, responseMessage.getToolCalls().size()); ChatCompletionsFunctionToolCall functionToolCall = (ChatCompletionsFunctionToolCall) responseMessage.getToolCalls().get(0); assertNotNull(functionToolCall); @@ -802,9 +800,9 @@ public void testGetChatCompletionsToolCallStreaming(HttpClient httpClient, OpenA assertEquals(1, toolCalls.size()); ChatCompletionsFunctionToolCall toolCall = (ChatCompletionsFunctionToolCall) toolCalls.get(0); FunctionCall functionCall = toolCall.getFunction(); - + // TODO: It used to be first stream event but now second event, in NonAzure // this data is only available in the first stream message, if at all - if (i == 0) { + if (i == 1) { content = chatChoice.getDelta().getContent(); functionName = functionCall.getName(); toolCallId = toolCall.getId(); diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/NonAzureOpenAISyncClientTest.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/NonAzureOpenAISyncClientTest.java index a89cf9e8066f0..89627ffcadd7d 100644 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/NonAzureOpenAISyncClientTest.java +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/NonAzureOpenAISyncClientTest.java @@ -3,7 +3,6 @@ package com.azure.ai.openai; -import com.azure.ai.openai.functions.MyFunctionCallArguments; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscription; import com.azure.ai.openai.models.AudioTranscriptionFormat; @@ -258,7 +257,7 @@ public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersi chatChoice, "MyFunction", MyFunctionCallArguments.class); - assertEquals(arguments.getLocation(), "San Francisco, CA"); + assertTrue(arguments.getLocation().contains("San Francisco")); assertEquals(arguments.getUnit(), "CELSIUS"); }); } @@ -679,7 +678,6 @@ public void testGetChatCompletionsToolCall(HttpClient httpClient, OpenAIServiceV assertNotNull(responseMessage); assertTrue(responseMessage.getContent() == null || responseMessage.getContent().isEmpty()); assertFalse(responseMessage.getToolCalls() == null || responseMessage.getToolCalls().isEmpty()); - assertEquals(1, responseMessage.getToolCalls().size()); ChatCompletionsFunctionToolCall functionToolCall = (ChatCompletionsFunctionToolCall) responseMessage.getToolCalls().get(0); assertNotNull(functionToolCall); @@ -729,9 +727,9 @@ public void testGetChatCompletionsToolCallStreaming(HttpClient httpClient, OpenA assertEquals(1, toolCalls.size()); ChatCompletionsFunctionToolCall toolCall = (ChatCompletionsFunctionToolCall) toolCalls.get(0); FunctionCall functionCall = toolCall.getFunction(); - - // this data is only available in the first stream message, if at all - if (i == 0) { + // TODO: It used to be first stream event but now second event, in NonAzure + // this data is only available in the second stream message, if at all + if (i == 1) { content = chatChoice.getDelta().getContent(); functionName = functionCall.getName(); toolCallId = toolCall.getId(); diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAIAsyncClientTest.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAIAsyncClientTest.java index 1a9b345d74fa8..d84cdcc74595d 100644 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAIAsyncClientTest.java +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAIAsyncClientTest.java @@ -3,7 +3,6 @@ package com.azure.ai.openai; -import com.azure.ai.openai.functions.MyFunctionCallArguments; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscriptionFormat; import com.azure.ai.openai.models.AudioTranscriptionTimestampGranularity; @@ -311,7 +310,7 @@ public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersi chatChoice, "MyFunction", MyFunctionCallArguments.class); - assertEquals(arguments.getLocation(), "San Francisco, CA"); + assertTrue(arguments.getLocation().contains("San Francisco")); assertEquals(arguments.getUnit(), "CELSIUS"); }) .verifyComplete(); @@ -942,9 +941,10 @@ public void testGetChatCompletionsToolCallStreaming(HttpClient httpClient, OpenA ChatCompletionsFunctionToolCall toolCall = (ChatCompletionsFunctionToolCall) toolCalls.get(0); FunctionCall functionCall = toolCall.getFunction(); - // this data is only available in the second stream message, if at all + // TODO: It used to be second stream event but now third event. + // this data is only available in the on second stream message, if at all // The first contains filter results mostly - if (i == 1) { + if (i == 2) { content = chatChoice.getDelta().getContent(); functionName = functionCall.getName(); toolCallId = toolCall.getId(); diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAIClientTestBase.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAIClientTestBase.java index a5bb32258a3fe..9cc50cf1282af 100644 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAIClientTestBase.java +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAIClientTestBase.java @@ -4,9 +4,9 @@ package com.azure.ai.openai; -import com.azure.ai.openai.functions.FutureTemperatureArguments; -import com.azure.ai.openai.functions.FutureTemperatureParameters; -import com.azure.ai.openai.functions.Parameters; +import com.azure.ai.openai.implementation.FutureTemperatureArguments; +import com.azure.ai.openai.implementation.FutureTemperatureParameters; +import com.azure.ai.openai.implementation.Parameters; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscription; import com.azure.ai.openai.models.AudioTranscriptionOptions; @@ -264,7 +264,7 @@ void contentFilterInputExceptionRunner(BiConsumer testRunner) { - testRunner.accept("gpt-3.5-turbo-0613", getChatMessagesWithFunction()); + testRunner.accept("gpt-4", getChatMessagesWithFunction()); } void getChatFunctionForRunner(BiConsumer testRunner) { diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAISyncClientTest.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAISyncClientTest.java index 421382ce516af..6f9ecdf7ac153 100644 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAISyncClientTest.java +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/OpenAISyncClientTest.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.ai.openai; -import com.azure.ai.openai.functions.MyFunctionCallArguments; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscription; import com.azure.ai.openai.models.AudioTranscriptionFormat; @@ -263,7 +262,7 @@ public void testChatFunctionAutoPreset(HttpClient httpClient, OpenAIServiceVersi chatChoice, "MyFunction", MyFunctionCallArguments.class); - assertEquals(arguments.getLocation(), "San Francisco, CA"); + assertTrue(arguments.getLocation().contains("San Francisco")); assertEquals(arguments.getUnit(), "CELSIUS"); }); } @@ -849,9 +848,10 @@ public void testGetChatCompletionsToolCallStreaming(HttpClient httpClient, OpenA ChatCompletionsFunctionToolCall toolCall = (ChatCompletionsFunctionToolCall) toolCalls.get(0); FunctionCall functionCall = toolCall.getFunction(); - // this data is only available in the second stream message, if at all + // TODO: It used to be second stream event but now third event. + // this data is only available in the third stream message, if at all // The first contains filter results mostly - if (i == 1) { + if (i == 2) { content = chatChoice.getDelta().getContent(); functionName = functionCall.getName(); toolCallId = toolCall.getId(); diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/FutureTemperatureArguments.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/FutureTemperatureArguments.java deleted file mode 100644 index 162eabd7c2d89..0000000000000 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/FutureTemperatureArguments.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.ai.openai.functions; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; - -public class FutureTemperatureArguments { - - @JsonProperty(value = "date") - private String date; - - @JsonProperty(value = "locationName") - private String locationName; - - @JsonProperty(value = "unit") - private String unit; - - @JsonCreator - public FutureTemperatureArguments(@JsonProperty(value = "locationName") String locationName, - @JsonProperty(value = "date") String date, - @JsonProperty(value = "unit") String unit) { - this.locationName = locationName; - this.date = date; - this.unit = unit; - } - - @JsonGetter - public String getDate() { - return date; - } - - @JsonSetter - public void setDate(String date) { - this.date = date; - } - - @JsonGetter - public String getLocationName() { - return locationName; - } - - @JsonSetter - public void setLocationName(String locationName) { - this.locationName = locationName; - } - - @JsonGetter - public String getUnit() { - return unit; - } - - @JsonSetter - public void setUnit(String unit) { - this.unit = unit; - } -} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/FutureTemperatureParameters.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/FutureTemperatureParameters.java deleted file mode 100644 index eaa4a58816bcd..0000000000000 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/FutureTemperatureParameters.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.ai.openai.functions; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; - -public class FutureTemperatureParameters { - - @JsonProperty(value = "type") - private String type = "object"; - - @JsonProperty(value = "properties") - private FutureTemperatureProperties properties = new FutureTemperatureProperties(); - - @JsonCreator - public FutureTemperatureParameters( - @JsonProperty(value = "type") - String type, - @JsonProperty(value = "properties") - FutureTemperatureProperties properties - ) { - this.type = type; - this.properties = properties; - } - - @JsonCreator - public FutureTemperatureParameters() {} - - @JsonGetter - public String getType() { - return type; - } - - @JsonSetter - public void setType(String type) { - this.type = type; - } - - @JsonGetter - public FutureTemperatureProperties getProperties() { - return properties; - } - - @JsonSetter - public void setProperties(FutureTemperatureProperties properties) { - this.properties = properties; - } -} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/FutureTemperatureProperties.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/FutureTemperatureProperties.java deleted file mode 100644 index fe932e79fcf0f..0000000000000 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/FutureTemperatureProperties.java +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.ai.openai.functions; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class FutureTemperatureProperties { - @JsonProperty - private StringField date = new StringField("The date of the weather forecast."); - - @JsonProperty - private StringField locationName = new StringField("The name of the location to forecast the weather for."); - - @JsonProperty - private StringField unit = new StringField("The unit of measurement for the temperature."); -} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Location.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Location.java deleted file mode 100644 index d36d19354572c..0000000000000 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Location.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.ai.openai.functions; - -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; - -public class Location { - - /** - * type defines the JSON type of the value that the service will request if a @FunctionCall is requested - */ - @JsonProperty(value = "type") - private String type = "string"; - - /** - * Examples provided in the description appear to be used verbatim. Such as "San Francisco, CA" - */ - @JsonProperty(value = "description") - private String description = "The city and state, e.g. San Francisco, CA"; - - @JsonGetter - public String getType() { - return type; - } - - @JsonSetter - public void setType(String type) { - this.type = type; - } - - @JsonGetter - public String getDescription() { - return description; - } - - @JsonSetter - public void setDescription(String description) { - this.description = description; - } -} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/MyFunctionCallArguments.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/MyFunctionCallArguments.java deleted file mode 100644 index 4cd3b0d19d126..0000000000000 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/MyFunctionCallArguments.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.ai.openai.functions; - -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; - -public class MyFunctionCallArguments { - @JsonProperty(value = "unit") - private String unit; - - @JsonProperty(value = "location") - private String location; - - @JsonGetter - public String getUnit() { - return unit; - } - - @JsonSetter - public void setUnit(String unit) { - this.unit = unit; - } - - @JsonGetter - public String getLocation() { - return location; - } - - @JsonSetter - public void setLocation(String location) { - this.location = location; - } -} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Parameters.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Parameters.java deleted file mode 100644 index b248c138094dd..0000000000000 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Parameters.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.ai.openai.functions; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; - -public class Parameters { - - @JsonProperty(value = "type") - private String type = "object"; - - @JsonProperty(value = "properties") - private Properties properties = new Properties(); - - @JsonCreator - public Parameters( - @JsonProperty(value = "type") - String type, - @JsonProperty(value = "properties") - Properties properties - ) { - this.type = type; - this.properties = properties; - } - - @JsonCreator - public Parameters() {} - - @JsonGetter - public String getType() { - return type; - } - - @JsonSetter - public void setType(String type) { - this.type = type; - } - - @JsonGetter - public Properties getProperties() { - return properties; - } - - @JsonSetter - public void setProperties(Properties properties) { - this.properties = properties; - } -} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Properties.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Properties.java deleted file mode 100644 index 4303e531cdbd5..0000000000000 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Properties.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.ai.openai.functions; - -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; - -public class Properties { - @JsonProperty(value = "unit") - private Unit unit = new Unit(); - - @JsonProperty - private Location location = new Location(); - - @JsonGetter - public Unit getUnit() { - return unit; - } - - @JsonSetter - public void setUnit(Unit unit) { - this.unit = unit; - } - - @JsonGetter - public Location getLocation() { - return location; - } - - @JsonSetter - public void setLocation(Location location) { - this.location = location; - } -} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/StringField.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/StringField.java deleted file mode 100644 index 9d075cd1a91c6..0000000000000 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/StringField.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.ai.openai.functions; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; - -public class StringField { - - @JsonProperty(value = "type") - private String type = "string"; - - @JsonProperty(value = "description") - private String description; - - @JsonCreator - public StringField( - @JsonProperty(value = "description") - String description - ) { - this.description = description; - } - - @JsonGetter - public String getType() { - return type; - } - - @JsonSetter - public void setType(String type) { - this.type = type; - } - - @JsonGetter - public String getDescription() { - return description; - } - - @JsonSetter - public void setDescription(String description) { - this.description = description; - } -} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Unit.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Unit.java deleted file mode 100644 index 6c3e92f94627e..0000000000000 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/functions/Unit.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.ai.openai.functions; - -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; - -import java.util.Arrays; -import java.util.List; - -public class Unit { - @JsonProperty(value = "type") - private String type = "string"; - - @JsonProperty(value = "enum") - private List enumValues = Arrays.asList("CELSIUS", "FAHRENHEIT"); - - @JsonGetter - public String getType() { - return type; - } - - @JsonSetter - public void setType(String type) { - this.type = type; - } - - @JsonGetter - public List getEnumValues() { - return enumValues; - } - - @JsonSetter - public void setEnumValues(List enumValues) { - this.enumValues = enumValues; - } -} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/FutureTemperatureArguments.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/FutureTemperatureArguments.java new file mode 100644 index 0000000000000..5161e031ad1b8 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/FutureTemperatureArguments.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.implementation; + +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; + +import java.io.IOException; + +public final class FutureTemperatureArguments implements JsonSerializable { + + private String date; + + private String locationName; + + private String unit; + + public FutureTemperatureArguments(String locationName, String date, String unit) { + this.locationName = locationName; + this.date = date; + this.unit = unit; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public String getLocationName() { + return locationName; + } + + public void setLocationName(String locationName) { + this.locationName = locationName; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("date", this.date); + jsonWriter.writeStringField("locationName", this.locationName); + jsonWriter.writeStringField("unit", this.unit); + return jsonWriter.writeEndObject(); + } + + public static FutureTemperatureArguments fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String locationName = null; + String date = null; + String unit = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("locationName".equals(fieldName)) { + locationName = reader.getString(); + } else if ("date".equals(fieldName)) { + date = reader.getString(); + } else if ("unit".equals(fieldName)) { + unit = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new FutureTemperatureArguments(locationName, date, unit); + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/FutureTemperatureParameters.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/FutureTemperatureParameters.java new file mode 100644 index 0000000000000..4277d1a958e6c --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/FutureTemperatureParameters.java @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.implementation; + +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; + +import java.io.IOException; + +public class FutureTemperatureParameters implements JsonSerializable { + + private String type = "object"; + + private FutureTemperatureProperties properties = new FutureTemperatureProperties(); + + public FutureTemperatureParameters(String type, FutureTemperatureProperties properties) { + this.type = type; + this.properties = properties; + } + + public FutureTemperatureParameters() {} + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public FutureTemperatureProperties getProperties() { + return properties; + } + + public void setProperties(FutureTemperatureProperties properties) { + this.properties = properties; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", "object"); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + public static FutureTemperatureParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FutureTemperatureParameters model = new FutureTemperatureParameters(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + model.setType(reader.getString()); + } else if ("properties".equals(fieldName)) { + model.setProperties(FutureTemperatureProperties.fromJson(reader)); + } else { + reader.skipChildren(); + } + } + return model; + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/FutureTemperatureProperties.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/FutureTemperatureProperties.java new file mode 100644 index 0000000000000..f6a16d04682f5 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/FutureTemperatureProperties.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.implementation; + +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; + +import java.io.IOException; + +public final class FutureTemperatureProperties implements JsonSerializable { + private StringField date = new StringField("The date of the weather forecast."); + + private StringField locationName = new StringField("The name of the location to forecast the weather for."); + + private StringField unit = new StringField("The unit of measurement for the temperature."); + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("date", this.date); + jsonWriter.writeJsonField("locationName", this.locationName); + jsonWriter.writeJsonField("unit", this.unit); + return jsonWriter.writeEndObject(); + } + + public static FutureTemperatureProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + StringField date = null; + StringField locationName = null; + StringField unit = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("date".equals(fieldName)) { + date = StringField.fromJson(jsonReader); + } else if ("locationName".equals(fieldName)) { + locationName = StringField.fromJson(jsonReader); + } else if ("unit".equals(fieldName)) { + unit = StringField.fromJson(jsonReader); + } else { + reader.skipChildren(); + } + } + FutureTemperatureProperties model = new FutureTemperatureProperties(); + model.date = date; + model.locationName = locationName; + model.unit = unit; + return model; + }); + } + +} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Location.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Location.java new file mode 100644 index 0000000000000..e8ac549219c5c --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Location.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.implementation; + +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; + +import java.io.IOException; + +public final class Location implements JsonSerializable { + + /** + * type defines the JSON type of the value that the service will request if a @FunctionCall is requested + */ + private String type = "string"; + + /** + * Examples provided in the description appear to be used verbatim. Such as "San Francisco, CA" + */ + private String description = "The city and state, e.g. San Francisco, CA"; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("description", this.description); + return jsonWriter.writeEndObject(); + } + + public static Location fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String type = null; + String description = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else { + reader.skipChildren(); + } + } + Location location = new Location(); + location.setType(type); + location.setDescription(description); + return location; + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Parameters.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Parameters.java new file mode 100644 index 0000000000000..9c6020f67dc02 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Parameters.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.implementation; + +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; + +import java.io.IOException; + +public final class Parameters implements JsonSerializable { + + private String type = "object"; + + private Properties properties = new Properties(); + + public Parameters(String type, Properties properties) { + this.type = type; + this.properties = properties; + } + + public Parameters() {} + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Properties getProperties() { + return properties; + } + + public void setProperties(Properties properties) { + this.properties = properties; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", "object"); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + public static Parameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String type = null; + Properties properties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("properties".equals(fieldName)) { + properties = Properties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new Parameters(type, properties); + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Properties.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Properties.java new file mode 100644 index 0000000000000..cb0eb583976d3 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Properties.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.implementation; + +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonWriter; + +import java.io.IOException; + +public final class Properties implements JsonSerializable { + private Unit unit = new Unit(); + + private Location location = new Location(); + + public Unit getUnit() { + return unit; + } + + public void setUnit(Unit unit) { + this.unit = unit; + } + + public Location getLocation() { + return location; + } + + public void setLocation(Location location) { + this.location = location; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("unit", this.unit); + jsonWriter.writeJsonField("location", this.location); + return jsonWriter.writeEndObject(); + } + + public static Properties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + + Unit unit = null; + Location location = null; + + while (reader.nextToken() != null) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("unit".equals(fieldName)) { + unit = Unit.fromJson(reader); + } else if ("location".equals(fieldName)) { + location = Location.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + Properties model = new Properties(); + model.setUnit(unit); + model.setLocation(location); + return model; + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/StringField.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/StringField.java new file mode 100644 index 0000000000000..183c40f9bb28c --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/StringField.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.implementation; + +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; + +import java.io.IOException; + +public final class StringField implements JsonSerializable { + + private String type = "string"; + + private String description; + + public StringField(String description) { + this.description = description; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("description", this.description); + return jsonWriter.writeEndObject(); + } + + public static StringField fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String value = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName) || "description".equals(fieldName)) { + value = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new StringField(value); + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/TestModel.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/TestModel.java index 57b0a51eb307f..7eafebc604b21 100644 --- a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/TestModel.java +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/TestModel.java @@ -3,16 +3,19 @@ package com.azure.ai.openai.implementation; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; + +import java.io.IOException; /** * Model class of testing serialization of server sent events. */ -public class TestModel { - @JsonProperty("name") +public final class TestModel implements JsonSerializable { private String name; - @JsonProperty("value") private String value; public String getName() { @@ -32,4 +35,30 @@ public TestModel setValue(String value) { this.value = value; return this; } + + @Override + public JsonWriter toJson(JsonWriter writer) throws IOException { + writer.writeStartObject(); + writer.writeStringField("name", name); + writer.writeStringField("value", value); + return writer.writeEndObject(); + } + + public static TestModel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + TestModel model = new TestModel(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + model.setName(reader.getString()); + } else if ("value".equals(fieldName)) { + model.setValue(reader.getString()); + } else { + reader.skipChildren(); + } + } + return model; + }); + } } diff --git a/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Unit.java b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Unit.java new file mode 100644 index 0000000000000..29db4dcb7a822 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/test/java/com/azure/ai/openai/implementation/Unit.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.implementation; + +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonWriter; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +public final class Unit implements JsonSerializable { + private String type = "string"; + + private List enumValues = Arrays.asList("CELSIUS", "FAHRENHEIT"); + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public List getEnumValues() { + return enumValues; + } + + public void setEnumValues(List enumValues) { + this.enumValues = enumValues; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeFieldName("enum"); + jsonWriter.writeStartArray(); + for (String value : this.enumValues) { + jsonWriter.writeString(value); + } + jsonWriter.writeEndArray(); + return jsonWriter.writeEndObject(); + } + + public static Unit fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String type = null; + List enumValues = null; + while (reader.nextToken() != null) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("enum".equals(fieldName)) { + enumValues = reader.readArray(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + Unit unit = new Unit(); + unit.setType(type); + unit.setEnumValues(enumValues); + return unit; + }); + } +} diff --git a/sdk/openai/azure-ai-openai/tsp-location.yaml b/sdk/openai/azure-ai-openai/tsp-location.yaml index 607e75f650bdd..78d1c954f7f03 100644 --- a/sdk/openai/azure-ai-openai/tsp-location.yaml +++ b/sdk/openai/azure-ai-openai/tsp-location.yaml @@ -1,5 +1,5 @@ directory: specification/cognitiveservices/OpenAI.Inference additionalDirectories: - specification/cognitiveservices/OpenAI.Authoring -commit: 6de0967fc50316e49610520f86917a25959cff64 +commit: 38749f76f08fd434885ce198b167c65058ab79f1 repo: Azure/azure-rest-api-specs diff --git a/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/pom.xml b/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/pom.xml index 174a6bbf7d50d..4739d84fbad7b 100644 --- a/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/pom.xml +++ b/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/orbital/azure-resourcemanager-orbital/pom.xml b/sdk/orbital/azure-resourcemanager-orbital/pom.xml index 5f64214f3e38e..91f799b066611 100644 --- a/sdk/orbital/azure-resourcemanager-orbital/pom.xml +++ b/sdk/orbital/azure-resourcemanager-orbital/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/pom.xml b/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/pom.xml index 8c94d9f82066f..1f26e567ddb22 100644 --- a/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/pom.xml +++ b/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/peering/azure-resourcemanager-peering/pom.xml b/sdk/peering/azure-resourcemanager-peering/pom.xml index 6b26ffc2d209e..502444fe2cfd9 100644 --- a/sdk/peering/azure-resourcemanager-peering/pom.xml +++ b/sdk/peering/azure-resourcemanager-peering/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/personalizer/azure-ai-personalizer/pom.xml b/sdk/personalizer/azure-ai-personalizer/pom.xml index b42bdbcc28a0a..e57ba41b5ee7a 100644 --- a/sdk/personalizer/azure-ai-personalizer/pom.xml +++ b/sdk/personalizer/azure-ai-personalizer/pom.xml @@ -49,31 +49,31 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -97,7 +97,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -112,7 +112,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/pom.xml b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/pom.xml index dfc392a267ca7..35842bff91625 100644 --- a/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/pom.xml +++ b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/policyinsights/azure-resourcemanager-policyinsights/pom.xml b/sdk/policyinsights/azure-resourcemanager-policyinsights/pom.xml index 50d0814f0b855..d9347c44efc06 100644 --- a/sdk/policyinsights/azure-resourcemanager-policyinsights/pom.xml +++ b/sdk/policyinsights/azure-resourcemanager-policyinsights/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/postgresql/azure-resourcemanager-postgresql/pom.xml b/sdk/postgresql/azure-resourcemanager-postgresql/pom.xml index 4f42e43e32a5d..51a294ffd9cb4 100644 --- a/sdk/postgresql/azure-resourcemanager-postgresql/pom.xml +++ b/sdk/postgresql/azure-resourcemanager-postgresql/pom.xml @@ -45,23 +45,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/pom.xml b/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/pom.xml index 14415548685cf..70b7963871900 100644 --- a/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/pom.xml +++ b/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/pom.xml b/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/pom.xml index 8e0b9bbce6952..e90760793c474 100644 --- a/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/pom.xml +++ b/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/providerhub/azure-resourcemanager-providerhub/pom.xml b/sdk/providerhub/azure-resourcemanager-providerhub/pom.xml index 0a88535b4ff87..d5d4418af3f95 100644 --- a/sdk/providerhub/azure-resourcemanager-providerhub/pom.xml +++ b/sdk/providerhub/azure-resourcemanager-providerhub/pom.xml @@ -50,12 +50,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure.resourcemanager @@ -66,13 +66,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/purview/azure-analytics-purview-administration/README.md b/sdk/purview/azure-analytics-purview-administration/README.md index 0b81c92d86959..f850e82e639d2 100644 --- a/sdk/purview/azure-analytics-purview-administration/README.md +++ b/sdk/purview/azure-analytics-purview-administration/README.md @@ -48,7 +48,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/purview/azure-analytics-purview-administration/pom.xml b/sdk/purview/azure-analytics-purview-administration/pom.xml index 394b99fb78cc8..d304cd4f11103 100644 --- a/sdk/purview/azure-analytics-purview-administration/pom.xml +++ b/sdk/purview/azure-analytics-purview-administration/pom.xml @@ -42,12 +42,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -60,13 +60,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/purview/azure-analytics-purview-catalog/README.md b/sdk/purview/azure-analytics-purview-catalog/README.md index 185f682fe8391..17d1980db0bc6 100644 --- a/sdk/purview/azure-analytics-purview-catalog/README.md +++ b/sdk/purview/azure-analytics-purview-catalog/README.md @@ -51,7 +51,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/purview/azure-analytics-purview-catalog/pom.xml b/sdk/purview/azure-analytics-purview-catalog/pom.xml index 1354ac17ab6cf..61cf77f866a36 100644 --- a/sdk/purview/azure-analytics-purview-catalog/pom.xml +++ b/sdk/purview/azure-analytics-purview-catalog/pom.xml @@ -42,12 +42,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -60,13 +60,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/purview/azure-analytics-purview-datamap/pom.xml b/sdk/purview/azure-analytics-purview-datamap/pom.xml index dfc64e4e1da95..751134a472d0b 100644 --- a/sdk/purview/azure-analytics-purview-datamap/pom.xml +++ b/sdk/purview/azure-analytics-purview-datamap/pom.xml @@ -50,12 +50,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -78,13 +78,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/purview/azure-analytics-purview-scanning/README.md b/sdk/purview/azure-analytics-purview-scanning/README.md index c1ca47efb968d..207359590b585 100644 --- a/sdk/purview/azure-analytics-purview-scanning/README.md +++ b/sdk/purview/azure-analytics-purview-scanning/README.md @@ -50,7 +50,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/purview/azure-analytics-purview-scanning/pom.xml b/sdk/purview/azure-analytics-purview-scanning/pom.xml index 0a8a066d4e2d0..fa56476d5c116 100644 --- a/sdk/purview/azure-analytics-purview-scanning/pom.xml +++ b/sdk/purview/azure-analytics-purview-scanning/pom.xml @@ -42,12 +42,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -66,13 +66,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/purview/azure-analytics-purview-sharing/pom.xml b/sdk/purview/azure-analytics-purview-sharing/pom.xml index d80e6b7990bc2..00e44549b7141 100644 --- a/sdk/purview/azure-analytics-purview-sharing/pom.xml +++ b/sdk/purview/azure-analytics-purview-sharing/pom.xml @@ -50,12 +50,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -72,13 +72,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/purview/azure-analytics-purview-workflow/README.md b/sdk/purview/azure-analytics-purview-workflow/README.md index 53c9c00ce0c93..1fef6f8c98b4b 100644 --- a/sdk/purview/azure-analytics-purview-workflow/README.md +++ b/sdk/purview/azure-analytics-purview-workflow/README.md @@ -29,7 +29,7 @@ To use the [UsernamePasswordCredential][username_password_credential] provider s com.azure azure-identity - 1.11.4 + 1.12.0 ``` diff --git a/sdk/purview/azure-analytics-purview-workflow/pom.xml b/sdk/purview/azure-analytics-purview-workflow/pom.xml index 623d5de865707..daad6ff141118 100644 --- a/sdk/purview/azure-analytics-purview-workflow/pom.xml +++ b/sdk/purview/azure-analytics-purview-workflow/pom.xml @@ -51,12 +51,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -73,13 +73,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/purview/azure-resourcemanager-purview/pom.xml b/sdk/purview/azure-resourcemanager-purview/pom.xml index 78f265051bb15..49b5a4f75fdb1 100644 --- a/sdk/purview/azure-resourcemanager-purview/pom.xml +++ b/sdk/purview/azure-resourcemanager-purview/pom.xml @@ -45,23 +45,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/quantum/azure-quantum-jobs/pom.xml b/sdk/quantum/azure-quantum-jobs/pom.xml index 9f9806b75b511..17e7fbe9be721 100644 --- a/sdk/quantum/azure-quantum-jobs/pom.xml +++ b/sdk/quantum/azure-quantum-jobs/pom.xml @@ -50,12 +50,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -70,13 +70,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/quantum/azure-quantum-jobs/src/test/java/com/azure/quantum/jobs/QuantumClientTestBase.java b/sdk/quantum/azure-quantum-jobs/src/test/java/com/azure/quantum/jobs/QuantumClientTestBase.java index 2299df6ca4a22..046f8777b2d0b 100644 --- a/sdk/quantum/azure-quantum-jobs/src/test/java/com/azure/quantum/jobs/QuantumClientTestBase.java +++ b/sdk/quantum/azure-quantum-jobs/src/test/java/com/azure/quantum/jobs/QuantumClientTestBase.java @@ -15,9 +15,13 @@ 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 com.azure.identity.DefaultAzureCredentialBuilder; public class QuantumClientTestBase extends TestProxyTestBase { + private static final ClientLogger LOGGER = new ClientLogger(QuantumClientTestBase.class); + private final String SANITIZED = "Sanitized"; private final String SUBSCRIPTION_ID = "00000000-0000-0000-0000-000000000000"; private final String RESOURCE_GROUP = "myresourcegroup"; @@ -27,12 +31,12 @@ public class QuantumClientTestBase extends TestProxyTestBase { QuantumClientBuilder getClientBuilder(HttpClient httpClient) { - System.out.println(String.format("Subscription id: %s", getSubscriptionId())); - System.out.println(String.format("Resource group: %s", getResourceGroup())); - System.out.println(String.format("Workspace: %s", getWorkspaceName())); - System.out.println(String.format("Location: %s", getLocation())); - System.out.println(String.format("Endpoint: %s", getEndpoint())); - System.out.println(String.format("Test mode: %s", getTestMode())); + LOGGER.log(LogLevel.VERBOSE, () -> "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/quantum/azure-resourcemanager-quantum/pom.xml b/sdk/quantum/azure-resourcemanager-quantum/pom.xml index 431f4f942d071..f7cfa6dff44cd 100644 --- a/sdk/quantum/azure-resourcemanager-quantum/pom.xml +++ b/sdk/quantum/azure-resourcemanager-quantum/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/qumulo/azure-resourcemanager-qumulo/pom.xml b/sdk/qumulo/azure-resourcemanager-qumulo/pom.xml index d8bbf40c7ca28..143ca3718da13 100644 --- a/sdk/qumulo/azure-resourcemanager-qumulo/pom.xml +++ b/sdk/qumulo/azure-resourcemanager-qumulo/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/quota/azure-resourcemanager-quota/pom.xml b/sdk/quota/azure-resourcemanager-quota/pom.xml index 654e6fb38ccde..eed293092753b 100644 --- a/sdk/quota/azure-resourcemanager-quota/pom.xml +++ b/sdk/quota/azure-resourcemanager-quota/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/recoveryservices/azure-resourcemanager-recoveryservices/pom.xml b/sdk/recoveryservices/azure-resourcemanager-recoveryservices/pom.xml index d10816d2fb278..4c52e850a8035 100644 --- a/sdk/recoveryservices/azure-resourcemanager-recoveryservices/pom.xml +++ b/sdk/recoveryservices/azure-resourcemanager-recoveryservices/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/pom.xml b/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/pom.xml index ec622e92c0d43..9c51ce3c136e8 100644 --- a/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/pom.xml +++ b/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/pom.xml b/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/pom.xml index f10f9a8824cfe..39726fb87eedb 100644 --- a/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/pom.xml +++ b/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/pom.xml b/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/pom.xml index f4ec105bb66d5..631a179dcd1e8 100644 --- a/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/pom.xml +++ b/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/redisenterprise/azure-resourcemanager-redisenterprise/pom.xml b/sdk/redisenterprise/azure-resourcemanager-redisenterprise/pom.xml index a8fdb85fafadd..16b9ec0585bbd 100644 --- a/sdk/redisenterprise/azure-resourcemanager-redisenterprise/pom.xml +++ b/sdk/redisenterprise/azure-resourcemanager-redisenterprise/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/relay/azure-resourcemanager-relay/pom.xml b/sdk/relay/azure-resourcemanager-relay/pom.xml index cf30757ef1ef2..28438a20288d9 100644 --- a/sdk/relay/azure-resourcemanager-relay/pom.xml +++ b/sdk/relay/azure-resourcemanager-relay/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/remoterendering/azure-mixedreality-remoterendering/pom.xml b/sdk/remoterendering/azure-mixedreality-remoterendering/pom.xml index a67697979d6be..fe520f42c35e3 100644 --- a/sdk/remoterendering/azure-mixedreality-remoterendering/pom.xml +++ b/sdk/remoterendering/azure-mixedreality-remoterendering/pom.xml @@ -31,7 +31,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -43,19 +43,19 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -91,13 +91,13 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-http-netty - 1.14.2 + 1.15.0 compile @@ -111,7 +111,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/reservations/azure-resourcemanager-reservations/pom.xml b/sdk/reservations/azure-resourcemanager-reservations/pom.xml index 073b1e61fbd25..929cea4bb8ab0 100644 --- a/sdk/reservations/azure-resourcemanager-reservations/pom.xml +++ b/sdk/reservations/azure-resourcemanager-reservations/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/resourceconnector/azure-resourcemanager-resourceconnector/pom.xml b/sdk/resourceconnector/azure-resourcemanager-resourceconnector/pom.xml index e6337bb72b797..e33e00de78e36 100644 --- a/sdk/resourceconnector/azure-resourcemanager-resourceconnector/pom.xml +++ b/sdk/resourceconnector/azure-resourcemanager-resourceconnector/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/resourcegraph/azure-resourcemanager-resourcegraph/pom.xml b/sdk/resourcegraph/azure-resourcemanager-resourcegraph/pom.xml index c1af612319eba..bc8726111fcc3 100644 --- a/sdk/resourcegraph/azure-resourcemanager-resourcegraph/pom.xml +++ b/sdk/resourcegraph/azure-resourcemanager-resourcegraph/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/resourcehealth/azure-resourcemanager-resourcehealth/pom.xml b/sdk/resourcehealth/azure-resourcemanager-resourcehealth/pom.xml index 928bc92101264..ba2e245aaee37 100644 --- a/sdk/resourcehealth/azure-resourcemanager-resourcehealth/pom.xml +++ b/sdk/resourcehealth/azure-resourcemanager-resourcehealth/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml b/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml index bfc291dec640a..e2c95f834ef94 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml @@ -96,7 +96,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test 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 e296384651bdd..812417c877c25 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/pom.xml b/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml index ef59fbbf95f87..24bd9eefa9e82 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml @@ -107,7 +107,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test 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 1d86fb736472f..066f8aaf53465 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/pom.xml b/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml index 9afecacf393cd..d494ba12f838e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml @@ -83,7 +83,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test 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 fdb1ce8debff7..3e50a823425b5 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-cdn/pom.xml b/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml index fb0f708371109..fe7d4b77ab3b0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml @@ -81,7 +81,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml b/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml index af9d3e6b689a6..45b735db3efb6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml @@ -112,7 +112,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test 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 770a9dbbf94c2..c6cead94f558f 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 e514f890fea4a..d8e3d7ae823ad 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 f6acacb5f6b45..6dbbc6ab4f035 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 aaf5daeb295a0..0f72c477a6045 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-containerinstance/pom.xml b/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml index b31d01fc035c5..baac256d8684a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml @@ -114,7 +114,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml b/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml index ec25d2a1308e2..7944fe5d0b0e2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml @@ -77,7 +77,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml b/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml index 208c83658d8b6..0965d172614bb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml @@ -79,7 +79,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test 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 f7a3930a4ef3d..66b802421cb96 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-cosmos/pom.xml b/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml index e3b3b6661d9a9..cce2ad8ef0dd6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml @@ -91,7 +91,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml b/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml index 9f32d6839ecbc..64e9166bbab9d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml @@ -87,7 +87,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml b/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml index 3e2c6c1549eca..c7de377933ba7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml @@ -81,7 +81,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml b/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml index b0a9f7554c171..cb2457610b007 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml @@ -69,7 +69,7 @@ com.azure azure-security-keyvault-keys - 4.8.2 + 4.8.3 com.azure @@ -103,7 +103,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml b/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml index 7cde991c40f15..35237f9e2f306 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml @@ -78,7 +78,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test 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 83d9d1561a15e..dee1fa063b696 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-msi/pom.xml b/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml index 1660606cdde1a..c8c080cda37f3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml @@ -73,7 +73,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-network/pom.xml b/sdk/resourcemanager/azure-resourcemanager-network/pom.xml index d985b890f40c8..e441f26de7fcc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-network/pom.xml @@ -81,7 +81,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml b/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml index 6247d3576aecd..3f31453d58e23 100644 --- a/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml @@ -41,12 +41,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml b/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml index 2d010f3074ef7..4952385c06f87 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml @@ -84,7 +84,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml b/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml index 5ac0f3d3cb184..400c8d119520f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml @@ -78,7 +78,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml b/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml index 98d5b7c5bb32a..0eb8b5b498aa9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml @@ -60,12 +60,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 org.slf4j @@ -88,7 +88,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test 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 d81b0ab2e2483..a4c355636f15f 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 4ce5407d25509..e2d2e643964bb 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 6d8b11398cb93..4df71ac7a2c57 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 f2a9814a8c92c..ba6710befa369 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 81f498b22ec26..d4ac227fff7cb 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 c1c13ddb0f922..743ff9dac62b9 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 92c73ad79bd66..f38f7f9ebd70c 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 761d0b600040f..dc72b43c093f2 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 c55b045693805..58fd15b5786ec 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 3b6a26bf6a3a8..419086bfe47cd 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 25d0e2c45f739..708b387ded373 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml @@ -64,17 +64,17 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-identity - 1.12.0 + 1.12.1 com.jcraft @@ -114,7 +114,7 @@ com.azure azure-cosmos - 4.58.0 + 4.59.0 com.azure @@ -156,7 +156,7 @@ com.azure azure-security-keyvault-administration - 4.5.2 + 4.5.3 test diff --git a/sdk/resourcemanager/azure-resourcemanager-search/pom.xml b/sdk/resourcemanager/azure-resourcemanager-search/pom.xml index c9df6bc8451e1..97a643d4c6769 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-search/pom.xml @@ -75,7 +75,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml b/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml index 4c838f1b07a38..5f5e3d96eb612 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml @@ -75,7 +75,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml b/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml index b68bf8147d82d..d8083fa7a2711 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml @@ -91,7 +91,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml b/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml index 210d270ad0c01..7d60c1900cb92 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml @@ -89,7 +89,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager-test/pom.xml b/sdk/resourcemanager/azure-resourcemanager-test/pom.xml index a555122036fa6..1546e20770505 100644 --- a/sdk/resourcemanager/azure-resourcemanager-test/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-test/pom.xml @@ -52,27 +52,27 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-identity - 1.12.0 + 1.12.1 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml index 3969f55be9346..6375f939fdc91 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml @@ -75,7 +75,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanager/azure-resourcemanager/pom.xml b/sdk/resourcemanager/azure-resourcemanager/pom.xml index b6bfe27c81dda..4af1b38e220eb 100644 --- a/sdk/resourcemanager/azure-resourcemanager/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager/pom.xml @@ -71,12 +71,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure.resourcemanager @@ -214,19 +214,19 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -282,7 +282,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 f47cf9a846e46..b481cdee77270 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 6f128a12344d3..dcab933c71301 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 882ce2ab1b5fc..a5f66e2472fe9 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 7bc709c81960d..190280a546ebf 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 79d98ea846f28..e896eea3d65cd 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 435a4212f5314..f5349b048003a 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 21b959dda73b1..e6ea71a52362f 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 8226a805d24f8..6c0edc1c24992 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 867de9bf56c5c..5683b621229c4 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 c8bf6a47f7051..952f5b94bd8a8 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 912d39298b15a..233d88f9c0acc 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 9cba6692de9f2..61e2ca7f1120e 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 e06d10395e171..49a9451b3333d 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 1897af7112fa9..27fe629849b1e 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 c31fdd62a87eb..01ae80cd352f4 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 0d0b58b9436d9..bcea20410bed5 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 645230b91671e..c0d30fe6f0bb2 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 6bdc52bdad116..e2030b9d13240 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 551f63d067310..1ea70731a0eac 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 d7cda788cbb8a..ef6b4a52d942b 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 bb847d6b08d6b..0f0035d66adc3 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 f0d9816d8828c..71dc359531418 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 85091cc9ec6be..d9a0908fb063f 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 b2f9099c59d8e..68448d74db779 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/resourcemanagerhybrid/README.md b/sdk/resourcemanagerhybrid/README.md index 4ee4b5ea0bf5b..5fbadce0fbac3 100644 --- a/sdk/resourcemanagerhybrid/README.md +++ b/sdk/resourcemanagerhybrid/README.md @@ -85,7 +85,7 @@ Azure Management Libraries require a `TokenCredential` implementation for authen com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/pom.xml index af6806056a18d..3055692f2bd41 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/pom.xml @@ -101,7 +101,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-authorization/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-authorization/pom.xml index 1fcc0db6c6ac8..10a811a0c097e 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-authorization/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-authorization/pom.xml @@ -81,7 +81,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-compute/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-compute/pom.xml index b0197d166f1d5..26c3fa65e7dd1 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-compute/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-compute/pom.xml @@ -111,7 +111,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-containerregistry/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-containerregistry/pom.xml index e4dd8241f3960..53c4452152357 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-containerregistry/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-containerregistry/pom.xml @@ -81,7 +81,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-containerservice/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-containerservice/pom.xml index 03002491fe286..f49a7a694b92e 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-containerservice/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-containerservice/pom.xml @@ -77,7 +77,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-dns/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-dns/pom.xml index 78839695a6dff..37b14911e4da6 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-dns/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-dns/pom.xml @@ -86,7 +86,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-eventhubs/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-eventhubs/pom.xml index e128abbcee8ad..28f0d00b2e91d 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-eventhubs/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-eventhubs/pom.xml @@ -80,7 +80,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-keyvault/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-keyvault/pom.xml index a43d40239894a..8f26f0c2c5d48 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-keyvault/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-keyvault/pom.xml @@ -68,7 +68,7 @@ com.azure azure-security-keyvault-keys - 4.8.2 + 4.8.3 com.azure @@ -102,7 +102,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-monitor/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-monitor/pom.xml index 29aa703f0e839..2ea6596073f42 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-monitor/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-monitor/pom.xml @@ -77,7 +77,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-network/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-network/pom.xml index c3676ad2a077d..31573344b9ac2 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-network/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-network/pom.xml @@ -81,7 +81,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-resources/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-resources/pom.xml index d0ff246eb8cc5..d380642457748 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-resources/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-resources/pom.xml @@ -59,12 +59,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 org.slf4j @@ -87,7 +87,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-storage/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-storage/pom.xml index fb8ec1260a9e7..3079a77c370ca 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-storage/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-storage/pom.xml @@ -74,7 +74,7 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-test/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-test/pom.xml index b335e80edfae5..017abe22e3b28 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-test/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-test/pom.xml @@ -52,32 +52,32 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-identity - 1.12.0 + 1.12.1 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager/pom.xml index e4c1bcb1e7230..15f9b3b902305 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager/pom.xml @@ -147,19 +147,19 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -196,7 +196,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/resourcemover/azure-resourcemanager-resourcemover/pom.xml b/sdk/resourcemover/azure-resourcemanager-resourcemover/pom.xml index b9e0c7c5734a0..8ec1e0775d68f 100644 --- a/sdk/resourcemover/azure-resourcemanager-resourcemover/pom.xml +++ b/sdk/resourcemover/azure-resourcemanager-resourcemover/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/README.md b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/README.md index 5ecc88649b94c..7af30a89a79f6 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/README.md @@ -51,7 +51,7 @@ with the Azure SDK, please include the `azure-identity` package: com.azure azure-identity - 1.11.4 + 1.12.0 ``` diff --git a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/pom.xml index c4e65876c09da..1b7e42a32cff6 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/pom.xml @@ -50,7 +50,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -104,13 +104,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/README.md b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/README.md index 414b018ad6cb7..2093523a716f0 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/README.md @@ -50,7 +50,7 @@ with the Azure SDK, please include the `azure-identity` package: com.azure azure-identity - 1.11.4 + 1.12.0 ``` diff --git a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/pom.xml index bf6dfddccc178..c90f60c49595e 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/pom.xml @@ -49,7 +49,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -85,13 +85,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/schemaregistry/azure-data-schemaregistry/README.md b/sdk/schemaregistry/azure-data-schemaregistry/README.md index 7f5f07a979082..3d5918679bc4e 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry/README.md @@ -75,7 +75,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.11.4 + 1.12.0 ``` diff --git a/sdk/schemaregistry/azure-data-schemaregistry/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry/pom.xml index b8725bb3f2664..672b5838c0113 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry/pom.xml @@ -52,12 +52,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -94,13 +94,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/scvmm/azure-resourcemanager-scvmm/pom.xml b/sdk/scvmm/azure-resourcemanager-scvmm/pom.xml index 9e1d26ea53d72..d2764ea6490ec 100644 --- a/sdk/scvmm/azure-resourcemanager-scvmm/pom.xml +++ b/sdk/scvmm/azure-resourcemanager-scvmm/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/search/azure-search-documents/pom.xml b/sdk/search/azure-search-documents/pom.xml index 2a92185aefa70..974db62b9f514 100644 --- a/sdk/search/azure-search-documents/pom.xml +++ b/sdk/search/azure-search-documents/pom.xml @@ -62,7 +62,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -72,12 +72,12 @@ com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java index d644e3ab9d016..5c6afb4e9221c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java @@ -1339,6 +1339,8 @@ static SearchRequest createSearchRequest(String searchText, SearchOptions option .setVectorQueries(vectorSearchOptions.getQueries()); } + request.setHybridSearch(options.getHybridSearch()); + return request; } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchOptions.java index 828361325615c..3849c63587573 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchOptions.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchOptions.java @@ -92,36 +92,6 @@ public final class SearchOptions implements JsonSerializable { */ private String scoringProfile; - /* - * Allows setting a separate search query that will be solely used for semantic reranking, semantic captions and - * semantic answers. Is useful for scenarios where there is a need to use different queries between the base - * retrieval and ranking phase, and the L2 semantic phase. - */ - private String semanticQuery; - - /* - * The name of the semantic configuration that lists which fields should be used for semantic ranking, captions, - * highlights, and answers - */ - private String semanticConfiguration; - - /* - * Allows the user to choose whether a semantic call should fail completely, or to return partial results - * (default). - */ - private SemanticErrorMode semanticErrorHandling; - - /* - * Allows the user to set an upper bound on the amount of time it takes for semantic enrichment to finish - * processing before the request fails. - */ - private Integer semanticMaxWaitInMilliseconds; - - /* - * Enables a debugging tool that can be used to further explore your search results. - */ - private QueryDebugMode debug; - /* * The list of field names to which to scope the full-text search. When using fielded search * (fieldName:searchExpression) in a full Lucene query, the field names of each fielded search expression take @@ -129,26 +99,6 @@ public final class SearchOptions implements JsonSerializable { */ private List searchFields; - /* - * The language of the query. - */ - private QueryLanguage queryLanguage; - - /* - * Improve search recall by spell-correcting individual search query terms. - */ - private QuerySpellerType speller; - - /* - * This parameter is only valid if the query type is `semantic`. If set, the query returns answers extracted from - * key passages in the highest ranked documents. The number of answers returned can be configured by appending the - * pipe character `|` followed by the `count-` option after the answers parameter value, such as - * `extractive|count-3`. Default count is 1. The confidence threshold can be configured by appending the pipe - * character `|` followed by the `threshold-` option after the answers parameter value, such - * as `extractive|threshold-0.9`. Default threshold is 0.7. - */ - private String answers; - /* * A value that specifies whether any or all of the search terms must be matched in order to count the document as * a match. @@ -189,6 +139,34 @@ public final class SearchOptions implements JsonSerializable { */ private Integer top; + /* + * The name of the semantic configuration that lists which fields should be used for semantic ranking, captions, + * highlights, and answers + */ + private String semanticConfiguration; + + /* + * Allows the user to choose whether a semantic call should fail completely, or to return partial results + * (default). + */ + private SemanticErrorMode semanticErrorHandling; + + /* + * Allows the user to set an upper bound on the amount of time it takes for semantic enrichment to finish + * processing before the request fails. + */ + private Integer semanticMaxWaitInMilliseconds; + + /* + * This parameter is only valid if the query type is `semantic`. If set, the query returns answers extracted from + * key passages in the highest ranked documents. The number of answers returned can be configured by appending the + * pipe character `|` followed by the `count-` option after the answers parameter value, such as + * `extractive|count-3`. Default count is 1. The confidence threshold can be configured by appending the pipe + * character `|` followed by the `threshold-` option after the answers parameter value, such + * as `extractive|threshold-0.9`. Default threshold is 0.7. + */ + private String answers; + /* * This parameter is only valid if the query type is `semantic`. If set, the query returns captions extracted from * key passages in the highest ranked documents. When Captions is set to `extractive`, highlighting is enabled by @@ -197,6 +175,28 @@ public final class SearchOptions implements JsonSerializable { */ private String captions; + /* + * Allows setting a separate search query that will be solely used for semantic reranking, semantic captions and + * semantic answers. Is useful for scenarios where there is a need to use different queries between the base + * retrieval and ranking phase, and the L2 semantic phase. + */ + private String semanticQuery; + + /* + * Enables a debugging tool that can be used to further explore your search results. + */ + private QueryDebugMode debug; + + /* + * The language of the query. + */ + private QueryLanguage queryLanguage; + + /* + * Improve search recall by spell-correcting individual search query terms. + */ + private QuerySpellerType speller; + /* * The list of field names used for semantic ranking. */ @@ -462,116 +462,6 @@ public SearchOptions setScoringProfile(String scoringProfile) { return this; } - /** - * Get the semanticQuery property: Allows setting a separate search query that will be solely used for semantic - * reranking, semantic captions and semantic answers. Is useful for scenarios where there is a need to use - * different queries between the base retrieval and ranking phase, and the L2 semantic phase. - * - * @return the semanticQuery value. - */ - public String getSemanticQuery() { - return this.semanticQuery; - } - - /** - * Set the semanticQuery property: Allows setting a separate search query that will be solely used for semantic - * reranking, semantic captions and semantic answers. Is useful for scenarios where there is a need to use - * different queries between the base retrieval and ranking phase, and the L2 semantic phase. - * - * @param semanticQuery the semanticQuery value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticQuery(String semanticQuery) { - this.semanticQuery = semanticQuery; - return this; - } - - /** - * Get the semanticConfiguration property: The name of the semantic configuration that lists which fields should be - * used for semantic ranking, captions, highlights, and answers. - * - * @return the semanticConfiguration value. - */ - public String getSemanticConfiguration() { - return this.semanticConfiguration; - } - - /** - * Set the semanticConfiguration property: The name of the semantic configuration that lists which fields should be - * used for semantic ranking, captions, highlights, and answers. - * - * @param semanticConfiguration the semanticConfiguration value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticConfiguration(String semanticConfiguration) { - this.semanticConfiguration = semanticConfiguration; - return this; - } - - /** - * Get the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail - * completely, or to return partial results (default). - * - * @return the semanticErrorHandling value. - */ - public SemanticErrorMode getSemanticErrorHandling() { - return this.semanticErrorHandling; - } - - /** - * Set the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail - * completely, or to return partial results (default). - * - * @param semanticErrorHandling the semanticErrorHandling value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticErrorHandling(SemanticErrorMode semanticErrorHandling) { - this.semanticErrorHandling = semanticErrorHandling; - return this; - } - - /** - * Get the semanticMaxWaitInMilliseconds property: Allows the user to set an upper bound on the amount of time it - * takes for semantic enrichment to finish processing before the request fails. - * - * @return the semanticMaxWaitInMilliseconds value. - */ - public Integer getSemanticMaxWaitInMilliseconds() { - return this.semanticMaxWaitInMilliseconds; - } - - /** - * Set the semanticMaxWaitInMilliseconds property: Allows the user to set an upper bound on the amount of time it - * takes for semantic enrichment to finish processing before the request fails. - * - * @param semanticMaxWaitInMilliseconds the semanticMaxWaitInMilliseconds value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticMaxWaitInMilliseconds(Integer semanticMaxWaitInMilliseconds) { - this.semanticMaxWaitInMilliseconds = semanticMaxWaitInMilliseconds; - return this; - } - - /** - * Get the debug property: Enables a debugging tool that can be used to further explore your search results. - * - * @return the debug value. - */ - public QueryDebugMode getDebug() { - return this.debug; - } - - /** - * Set the debug property: Enables a debugging tool that can be used to further explore your search results. - * - * @param debug the debug value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setDebug(QueryDebugMode debug) { - this.debug = debug; - return this; - } - /** * Get the searchFields property: The list of field names to which to scope the full-text search. When using * fielded search (fieldName:searchExpression) in a full Lucene query, the field names of each fielded search @@ -596,76 +486,6 @@ public SearchOptions setSearchFields(List searchFields) { return this; } - /** - * Get the queryLanguage property: The language of the query. - * - * @return the queryLanguage value. - */ - public QueryLanguage getQueryLanguage() { - return this.queryLanguage; - } - - /** - * Set the queryLanguage property: The language of the query. - * - * @param queryLanguage the queryLanguage value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setQueryLanguage(QueryLanguage queryLanguage) { - this.queryLanguage = queryLanguage; - return this; - } - - /** - * Get the speller property: Improve search recall by spell-correcting individual search query terms. - * - * @return the speller value. - */ - public QuerySpellerType getSpeller() { - return this.speller; - } - - /** - * Set the speller property: Improve search recall by spell-correcting individual search query terms. - * - * @param speller the speller value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSpeller(QuerySpellerType speller) { - this.speller = speller; - return this; - } - - /** - * Get the answers property: This parameter is only valid if the query type is `semantic`. If set, the query - * returns answers extracted from key passages in the highest ranked documents. The number of answers returned can - * be configured by appending the pipe character `|` followed by the `count-<number of answers>` option after - * the answers parameter value, such as `extractive|count-3`. Default count is 1. The confidence threshold can be - * configured by appending the pipe character `|` followed by the `threshold-<confidence threshold>` option - * after the answers parameter value, such as `extractive|threshold-0.9`. Default threshold is 0.7. - * - * @return the answers value. - */ - public String getAnswers() { - return this.answers; - } - - /** - * Set the answers property: This parameter is only valid if the query type is `semantic`. If set, the query - * returns answers extracted from key passages in the highest ranked documents. The number of answers returned can - * be configured by appending the pipe character `|` followed by the `count-<number of answers>` option after - * the answers parameter value, such as `extractive|count-3`. Default count is 1. The confidence threshold can be - * configured by appending the pipe character `|` followed by the `threshold-<confidence threshold>` option - * after the answers parameter value, such as `extractive|threshold-0.9`. Default threshold is 0.7. - * - * @param answers the answers value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setAnswers(String answers) { - this.answers = answers; - return this; - } - /** * Get the searchMode property: A value that specifies whether any or all of the search terms must be matched in * order to count the document as a match. @@ -808,6 +628,102 @@ public SearchOptions setTop(Integer top) { return this; } + /** + * Get the semanticConfiguration property: The name of the semantic configuration that lists which fields should be + * used for semantic ranking, captions, highlights, and answers. + * + * @return the semanticConfiguration value. + */ + public String getSemanticConfiguration() { + return this.semanticConfiguration; + } + + /** + * Set the semanticConfiguration property: The name of the semantic configuration that lists which fields should be + * used for semantic ranking, captions, highlights, and answers. + * + * @param semanticConfiguration the semanticConfiguration value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setSemanticConfiguration(String semanticConfiguration) { + this.semanticConfiguration = semanticConfiguration; + return this; + } + + /** + * Get the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail + * completely, or to return partial results (default). + * + * @return the semanticErrorHandling value. + */ + public SemanticErrorMode getSemanticErrorHandling() { + return this.semanticErrorHandling; + } + + /** + * Set the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail + * completely, or to return partial results (default). + * + * @param semanticErrorHandling the semanticErrorHandling value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setSemanticErrorHandling(SemanticErrorMode semanticErrorHandling) { + this.semanticErrorHandling = semanticErrorHandling; + return this; + } + + /** + * Get the semanticMaxWaitInMilliseconds property: Allows the user to set an upper bound on the amount of time it + * takes for semantic enrichment to finish processing before the request fails. + * + * @return the semanticMaxWaitInMilliseconds value. + */ + public Integer getSemanticMaxWaitInMilliseconds() { + return this.semanticMaxWaitInMilliseconds; + } + + /** + * Set the semanticMaxWaitInMilliseconds property: Allows the user to set an upper bound on the amount of time it + * takes for semantic enrichment to finish processing before the request fails. + * + * @param semanticMaxWaitInMilliseconds the semanticMaxWaitInMilliseconds value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setSemanticMaxWaitInMilliseconds(Integer semanticMaxWaitInMilliseconds) { + this.semanticMaxWaitInMilliseconds = semanticMaxWaitInMilliseconds; + return this; + } + + /** + * Get the answers property: This parameter is only valid if the query type is `semantic`. If set, the query + * returns answers extracted from key passages in the highest ranked documents. The number of answers returned can + * be configured by appending the pipe character `|` followed by the `count-<number of answers>` option after + * the answers parameter value, such as `extractive|count-3`. Default count is 1. The confidence threshold can be + * configured by appending the pipe character `|` followed by the `threshold-<confidence threshold>` option + * after the answers parameter value, such as `extractive|threshold-0.9`. Default threshold is 0.7. + * + * @return the answers value. + */ + public String getAnswers() { + return this.answers; + } + + /** + * Set the answers property: This parameter is only valid if the query type is `semantic`. If set, the query + * returns answers extracted from key passages in the highest ranked documents. The number of answers returned can + * be configured by appending the pipe character `|` followed by the `count-<number of answers>` option after + * the answers parameter value, such as `extractive|count-3`. Default count is 1. The confidence threshold can be + * configured by appending the pipe character `|` followed by the `threshold-<confidence threshold>` option + * after the answers parameter value, such as `extractive|threshold-0.9`. Default threshold is 0.7. + * + * @param answers the answers value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setAnswers(String answers) { + this.answers = answers; + return this; + } + /** * Get the captions property: This parameter is only valid if the query type is `semantic`. If set, the query * returns captions extracted from key passages in the highest ranked documents. When Captions is set to @@ -834,6 +750,90 @@ public SearchOptions setCaptions(String captions) { return this; } + /** + * Get the semanticQuery property: Allows setting a separate search query that will be solely used for semantic + * reranking, semantic captions and semantic answers. Is useful for scenarios where there is a need to use + * different queries between the base retrieval and ranking phase, and the L2 semantic phase. + * + * @return the semanticQuery value. + */ + public String getSemanticQuery() { + return this.semanticQuery; + } + + /** + * Set the semanticQuery property: Allows setting a separate search query that will be solely used for semantic + * reranking, semantic captions and semantic answers. Is useful for scenarios where there is a need to use + * different queries between the base retrieval and ranking phase, and the L2 semantic phase. + * + * @param semanticQuery the semanticQuery value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setSemanticQuery(String semanticQuery) { + this.semanticQuery = semanticQuery; + return this; + } + + /** + * Get the debug property: Enables a debugging tool that can be used to further explore your search results. + * + * @return the debug value. + */ + public QueryDebugMode getDebug() { + return this.debug; + } + + /** + * Set the debug property: Enables a debugging tool that can be used to further explore your search results. + * + * @param debug the debug value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setDebug(QueryDebugMode debug) { + this.debug = debug; + return this; + } + + /** + * Get the queryLanguage property: The language of the query. + * + * @return the queryLanguage value. + */ + public QueryLanguage getQueryLanguage() { + return this.queryLanguage; + } + + /** + * Set the queryLanguage property: The language of the query. + * + * @param queryLanguage the queryLanguage value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setQueryLanguage(QueryLanguage queryLanguage) { + this.queryLanguage = queryLanguage; + return this; + } + + /** + * Get the speller property: Improve search recall by spell-correcting individual search query terms. + * + * @return the speller value. + */ + public QuerySpellerType getSpeller() { + return this.speller; + } + + /** + * Set the speller property: Improve search recall by spell-correcting individual search query terms. + * + * @param speller the speller value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setSpeller(QuerySpellerType speller) { + this.speller = speller; + return this; + } + /** * Get the semanticFields property: The list of field names used for semantic ranking. * @@ -870,16 +870,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeArrayField("ScoringParameters", this.scoringParameters, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("scoringProfile", this.scoringProfile); - jsonWriter.writeStringField("semanticQuery", this.semanticQuery); - jsonWriter.writeStringField("semanticConfiguration", this.semanticConfiguration); - jsonWriter.writeStringField("semanticErrorHandling", - this.semanticErrorHandling == null ? null : this.semanticErrorHandling.toString()); - jsonWriter.writeNumberField("semanticMaxWaitInMilliseconds", this.semanticMaxWaitInMilliseconds); - jsonWriter.writeStringField("debug", this.debug == null ? null : this.debug.toString()); jsonWriter.writeArrayField("searchFields", this.searchFields, (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("queryLanguage", this.queryLanguage == null ? null : this.queryLanguage.toString()); - jsonWriter.writeStringField("speller", this.speller == null ? null : this.speller.toString()); - jsonWriter.writeStringField("answers", this.answers); jsonWriter.writeStringField("searchMode", this.searchMode == null ? null : this.searchMode.toString()); jsonWriter.writeStringField("scoringStatistics", this.scoringStatistics == null ? null : this.scoringStatistics.toString()); @@ -887,7 +878,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeArrayField("$select", this.select, (writer, element) -> writer.writeString(element)); jsonWriter.writeNumberField("$skip", this.skip); jsonWriter.writeNumberField("$top", this.top); + jsonWriter.writeStringField("semanticConfiguration", this.semanticConfiguration); + jsonWriter.writeStringField("semanticErrorHandling", + this.semanticErrorHandling == null ? null : this.semanticErrorHandling.toString()); + jsonWriter.writeNumberField("semanticMaxWaitInMilliseconds", this.semanticMaxWaitInMilliseconds); + jsonWriter.writeStringField("answers", this.answers); jsonWriter.writeStringField("captions", this.captions); + jsonWriter.writeStringField("semanticQuery", this.semanticQuery); + jsonWriter.writeStringField("debug", this.debug == null ? null : this.debug.toString()); + jsonWriter.writeStringField("queryLanguage", this.queryLanguage == null ? null : this.queryLanguage.toString()); + jsonWriter.writeStringField("speller", this.speller == null ? null : this.speller.toString()); jsonWriter.writeArrayField("semanticFields", this.semanticFields, (writer, element) -> writer.writeString(element)); return jsonWriter.writeEndObject(); @@ -933,25 +933,9 @@ public static SearchOptions fromJson(JsonReader jsonReader) throws IOException { deserializedSearchOptions.scoringParameters = scoringParameters; } else if ("scoringProfile".equals(fieldName)) { deserializedSearchOptions.scoringProfile = reader.getString(); - } else if ("semanticQuery".equals(fieldName)) { - deserializedSearchOptions.semanticQuery = reader.getString(); - } else if ("semanticConfiguration".equals(fieldName)) { - deserializedSearchOptions.semanticConfiguration = reader.getString(); - } else if ("semanticErrorHandling".equals(fieldName)) { - deserializedSearchOptions.semanticErrorHandling = SemanticErrorMode.fromString(reader.getString()); - } else if ("semanticMaxWaitInMilliseconds".equals(fieldName)) { - deserializedSearchOptions.semanticMaxWaitInMilliseconds = reader.getNullable(JsonReader::getInt); - } else if ("debug".equals(fieldName)) { - deserializedSearchOptions.debug = QueryDebugMode.fromString(reader.getString()); } else if ("searchFields".equals(fieldName)) { List searchFields = reader.readArray(reader1 -> reader1.getString()); deserializedSearchOptions.searchFields = searchFields; - } else if ("queryLanguage".equals(fieldName)) { - deserializedSearchOptions.queryLanguage = QueryLanguage.fromString(reader.getString()); - } else if ("speller".equals(fieldName)) { - deserializedSearchOptions.speller = QuerySpellerType.fromString(reader.getString()); - } else if ("answers".equals(fieldName)) { - deserializedSearchOptions.answers = reader.getString(); } else if ("searchMode".equals(fieldName)) { deserializedSearchOptions.searchMode = SearchMode.fromString(reader.getString()); } else if ("scoringStatistics".equals(fieldName)) { @@ -965,8 +949,24 @@ public static SearchOptions fromJson(JsonReader jsonReader) throws IOException { deserializedSearchOptions.skip = reader.getNullable(JsonReader::getInt); } else if ("$top".equals(fieldName)) { deserializedSearchOptions.top = reader.getNullable(JsonReader::getInt); + } else if ("semanticConfiguration".equals(fieldName)) { + deserializedSearchOptions.semanticConfiguration = reader.getString(); + } else if ("semanticErrorHandling".equals(fieldName)) { + deserializedSearchOptions.semanticErrorHandling = SemanticErrorMode.fromString(reader.getString()); + } else if ("semanticMaxWaitInMilliseconds".equals(fieldName)) { + deserializedSearchOptions.semanticMaxWaitInMilliseconds = reader.getNullable(JsonReader::getInt); + } else if ("answers".equals(fieldName)) { + deserializedSearchOptions.answers = reader.getString(); } else if ("captions".equals(fieldName)) { deserializedSearchOptions.captions = reader.getString(); + } else if ("semanticQuery".equals(fieldName)) { + deserializedSearchOptions.semanticQuery = reader.getString(); + } else if ("debug".equals(fieldName)) { + deserializedSearchOptions.debug = QueryDebugMode.fromString(reader.getString()); + } else if ("queryLanguage".equals(fieldName)) { + deserializedSearchOptions.queryLanguage = QueryLanguage.fromString(reader.getString()); + } else if ("speller".equals(fieldName)) { + deserializedSearchOptions.speller = QuerySpellerType.fromString(reader.getString()); } else if ("semanticFields".equals(fieldName)) { List semanticFields = reader.readArray(reader1 -> reader1.getString()); deserializedSearchOptions.semanticFields = semanticFields; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchRequest.java index 54c80cddaa31a..a6a0bcc804ed7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchRequest.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchRequest.java @@ -11,6 +11,7 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.models.HybridSearch; import com.azure.search.documents.models.QueryDebugMode; import com.azure.search.documents.models.QueryLanguage; import com.azure.search.documents.models.QuerySpellerType; @@ -223,6 +224,11 @@ public final class SearchRequest implements JsonSerializable { */ private VectorFilterMode vectorFilterMode; + /* + * The query parameters to configure hybrid search behaviors. + */ + private HybridSearch hybridSearch; + /** * Creates an instance of SearchRequest class. */ @@ -945,6 +951,26 @@ public SearchRequest setVectorFilterMode(VectorFilterMode vectorFilterMode) { return this; } + /** + * Get the hybridSearch property: The query parameters to configure hybrid search behaviors. + * + * @return the hybridSearch value. + */ + public HybridSearch getHybridSearch() { + return this.hybridSearch; + } + + /** + * Set the hybridSearch property: The query parameters to configure hybrid search behaviors. + * + * @param hybridSearch the hybridSearch value to set. + * @return the SearchRequest object itself. + */ + public SearchRequest setHybridSearch(HybridSearch hybridSearch) { + this.hybridSearch = hybridSearch; + return this; + } + @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -983,6 +1009,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeArrayField("vectorQueries", this.vectorQueries, (writer, element) -> writer.writeJson(element)); jsonWriter.writeStringField("vectorFilterMode", this.vectorFilterMode == null ? null : this.vectorFilterMode.toString()); + jsonWriter.writeJsonField("hybridSearch", this.hybridSearch); return jsonWriter.writeEndObject(); } @@ -1066,6 +1093,8 @@ public static SearchRequest fromJson(JsonReader jsonReader) throws IOException { deserializedSearchRequest.vectorQueries = vectorQueries; } else if ("vectorFilterMode".equals(fieldName)) { deserializedSearchRequest.vectorFilterMode = VectorFilterMode.fromString(reader.getString()); + } else if ("hybridSearch".equals(fieldName)) { + deserializedSearchRequest.hybridSearch = HybridSearch.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/VectorQueryKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/VectorQueryKind.java index 76abc5440ab00..353bf77cd623f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/VectorQueryKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/VectorQueryKind.java @@ -23,6 +23,16 @@ public final class VectorQueryKind extends ExpandableStringEnum */ public static final VectorQueryKind TEXT = fromString("text"); + /** + * Vector query where an url that represents an image value that needs to be vectorized is provided. + */ + public static final VectorQueryKind IMAGE_URL = fromString("imageUrl"); + + /** + * Vector query where a base 64 encoded binary of an image that needs to be vectorized is provided. + */ + public static final VectorQueryKind IMAGE_BINARY = fromString("imageBinary"); + /** * Creates a new instance of VectorQueryKind value. * 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 62040f0d53c96..47680fb5bf860 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 @@ -18,6 +18,7 @@ import com.azure.search.documents.indexes.models.LexicalNormalizerName; import com.azure.search.documents.indexes.models.SearchField; import com.azure.search.documents.indexes.models.SearchFieldDataType; +import com.azure.search.documents.indexes.models.VectorEncodingFormat; import reactor.util.annotation.Nullable; import java.lang.annotation.Annotation; @@ -279,6 +280,7 @@ private static SearchField enrichWithAnnotation(SearchField searchField, Member String normalizerName; Integer vectorSearchDimensions = null; String vectorSearchProfileName = null; + String vectorEncodingFormat = null; if (simpleField != null) { key = simpleField.isKey(); @@ -304,6 +306,8 @@ private static SearchField enrichWithAnnotation(SearchField searchField, Member ? searchableField.vectorSearchDimensions() : null; vectorSearchProfileName = CoreUtils.isNullOrEmpty(searchableField.vectorSearchProfileName()) ? null : searchableField.vectorSearchProfileName(); + vectorEncodingFormat = CoreUtils.isNullOrEmpty(searchableField.vectorEncodingFormat()) + ? null : searchableField.vectorEncodingFormat(); } StringBuilder errorMessage = new StringBuilder(); @@ -314,6 +318,7 @@ private static SearchField enrichWithAnnotation(SearchField searchField, Member boolean hasSearchAnalyzerName = !CoreUtils.isNullOrEmpty(searchAnalyzerName); boolean hasIndexAnalyzerName = !CoreUtils.isNullOrEmpty(indexAnalyzerName); boolean hasNormalizerName = !CoreUtils.isNullOrEmpty(normalizerName); + boolean hasVectorEncodingFormat = !CoreUtils.isNullOrEmpty(vectorEncodingFormat); if (searchable) { if (!isSearchableType) { errorMessage.append("SearchField can only be used on 'Edm.String', 'Collection(Edm.String)', or " @@ -371,6 +376,10 @@ private static SearchField enrichWithAnnotation(SearchField searchField, Member searchField.setNormalizerName(LexicalNormalizerName.fromString(normalizerName)); } + if (hasVectorEncodingFormat) { + searchField.setVectorEncodingFormat(VectorEncodingFormat.fromString(vectorEncodingFormat)); + } + if (!CoreUtils.isNullOrEmpty(synonymMapNames)) { List synonymMaps = Arrays.stream(searchableField.synonymMapNames()) .filter(synonym -> !synonym.trim().isEmpty()) diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java index 5b6c7ce6b7f1b..0895ee565934d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java @@ -8,6 +8,7 @@ import com.azure.search.documents.indexes.models.LexicalNormalizerName; import com.azure.search.documents.indexes.models.SearchField; import com.azure.search.documents.indexes.models.SynonymMap; +import com.azure.search.documents.indexes.models.VectorEncodingFormat; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -126,4 +127,12 @@ */ String vectorSearchProfileName() default ""; + /** + * A {@link VectorEncodingFormat} to be associated with the {@link SearchField field}. + *

+ * If the value is empty, the field won't have a {@link SearchField#getVectorEncodingFormat()} value. + * + * @return The {@link VectorEncodingFormat} that will be associated with the {@link SearchField field}. + */ + String vectorEncodingFormat() default ""; } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionParameters.java new file mode 100644 index 0000000000000..154f3b7b18400 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionParameters.java @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Specifies the AI Services Vision parameters for vectorizing a query image or text. + */ +@Fluent +public final class AIServicesVisionParameters implements JsonSerializable { + /* + * The version of the model to use when calling the AI Services Vision service. It will default to the latest + * available when not specified. + */ + private final String modelVersion; + + /* + * The resource URI of the AI Services resource. + */ + private final String resourceUri; + + /* + * API key of the designated AI Services resource. + */ + private String apiKey; + + /* + * The user-assigned managed identity used for outbound connections. If an authResourceId is provided and it's not + * specified, the system-assigned managed identity is used. On updates to the index, if the identity is + * unspecified, the value remains unchanged. If set to "none", the value of this property is cleared. + */ + private SearchIndexerDataIdentity authIdentity; + + /** + * Creates an instance of AIServicesVisionParameters class. + * + * @param modelVersion the modelVersion value to set. + * @param resourceUri the resourceUri value to set. + */ + public AIServicesVisionParameters(String modelVersion, String resourceUri) { + this.modelVersion = modelVersion; + this.resourceUri = resourceUri; + } + + /** + * Get the modelVersion property: The version of the model to use when calling the AI Services Vision service. It + * will default to the latest available when not specified. + * + * @return the modelVersion value. + */ + public String getModelVersion() { + return this.modelVersion; + } + + /** + * Get the resourceUri property: The resource URI of the AI Services resource. + * + * @return the resourceUri value. + */ + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the apiKey property: API key of the designated AI Services resource. + * + * @return the apiKey value. + */ + public String getApiKey() { + return this.apiKey; + } + + /** + * Set the apiKey property: API key of the designated AI Services resource. + * + * @param apiKey the apiKey value to set. + * @return the AIServicesVisionParameters object itself. + */ + public AIServicesVisionParameters setApiKey(String apiKey) { + this.apiKey = apiKey; + return this; + } + + /** + * Get the authIdentity property: The user-assigned managed identity used for outbound connections. If an + * authResourceId is provided and it's not specified, the system-assigned managed identity is used. On updates to + * the index, if the identity is unspecified, the value remains unchanged. If set to "none", the value of this + * property is cleared. + * + * @return the authIdentity value. + */ + public SearchIndexerDataIdentity getAuthIdentity() { + return this.authIdentity; + } + + /** + * Set the authIdentity property: The user-assigned managed identity used for outbound connections. If an + * authResourceId is provided and it's not specified, the system-assigned managed identity is used. On updates to + * the index, if the identity is unspecified, the value remains unchanged. If set to "none", the value of this + * property is cleared. + * + * @param authIdentity the authIdentity value to set. + * @return the AIServicesVisionParameters object itself. + */ + public AIServicesVisionParameters setAuthIdentity(SearchIndexerDataIdentity authIdentity) { + this.authIdentity = authIdentity; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("modelVersion", this.modelVersion); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("apiKey", this.apiKey); + jsonWriter.writeJsonField("authIdentity", this.authIdentity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AIServicesVisionParameters from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AIServicesVisionParameters 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 AIServicesVisionParameters. + */ + public static AIServicesVisionParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean modelVersionFound = false; + String modelVersion = null; + boolean resourceUriFound = false; + String resourceUri = null; + String apiKey = null; + SearchIndexerDataIdentity authIdentity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("modelVersion".equals(fieldName)) { + modelVersion = reader.getString(); + modelVersionFound = true; + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + resourceUriFound = true; + } else if ("apiKey".equals(fieldName)) { + apiKey = reader.getString(); + } else if ("authIdentity".equals(fieldName)) { + authIdentity = SearchIndexerDataIdentity.fromJson(reader); + } else { + reader.skipChildren(); + } + } + if (modelVersionFound && resourceUriFound) { + AIServicesVisionParameters deserializedAIServicesVisionParameters + = new AIServicesVisionParameters(modelVersion, resourceUri); + deserializedAIServicesVisionParameters.apiKey = apiKey; + deserializedAIServicesVisionParameters.authIdentity = authIdentity; + + return deserializedAIServicesVisionParameters; + } + List missingProperties = new ArrayList<>(); + if (!modelVersionFound) { + missingProperties.add("modelVersion"); + } + if (!resourceUriFound) { + missingProperties.add("resourceUri"); + } + + throw new IllegalStateException( + "Missing required property/properties: " + String.join(", ", missingProperties)); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionVectorizer.java new file mode 100644 index 0000000000000..7f1befda2497f --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionVectorizer.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Specifies the AI Services Vision parameters for vectorizing a query image or text. + */ +@Fluent +public final class AIServicesVisionVectorizer extends VectorSearchVectorizer { + /* + * Contains the parameters specific to AI Services Vision embedding vectorization. + */ + private AIServicesVisionParameters aIServicesVisionParameters; + + /** + * Creates an instance of AIServicesVisionVectorizer class. + * + * @param name the name value to set. + */ + public AIServicesVisionVectorizer(String name) { + super(name); + } + + /** + * Get the aIServicesVisionParameters property: Contains the parameters specific to AI Services Vision embedding + * vectorization. + * + * @return the aIServicesVisionParameters value. + */ + public AIServicesVisionParameters getAIServicesVisionParameters() { + return this.aIServicesVisionParameters; + } + + /** + * Set the aIServicesVisionParameters property: Contains the parameters specific to AI Services Vision embedding + * vectorization. + * + * @param aIServicesVisionParameters the aIServicesVisionParameters value to set. + * @return the AIServicesVisionVectorizer object itself. + */ + public AIServicesVisionVectorizer + setAIServicesVisionParameters(AIServicesVisionParameters aIServicesVisionParameters) { + this.aIServicesVisionParameters = aIServicesVisionParameters; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kind", VectorSearchVectorizerKind.AISERVICES_VISION == null ? null + : VectorSearchVectorizerKind.AISERVICES_VISION.toString()); + jsonWriter.writeStringField("name", getName()); + jsonWriter.writeJsonField("aiServicesVisionParameters", this.aIServicesVisionParameters); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AIServicesVisionVectorizer from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AIServicesVisionVectorizer 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 AIServicesVisionVectorizer. + */ + public static AIServicesVisionVectorizer fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean nameFound = false; + String name = null; + AIServicesVisionParameters aIServicesVisionParameters = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("kind".equals(fieldName)) { + String kind = reader.getString(); + if (!"aiServicesVision".equals(kind)) { + throw new IllegalStateException( + "'kind' was expected to be non-null and equal to 'aiServicesVision'. The found 'kind' was '" + + kind + "'."); + } + } else if ("name".equals(fieldName)) { + name = reader.getString(); + nameFound = true; + } else if ("aiServicesVisionParameters".equals(fieldName)) { + aIServicesVisionParameters = AIServicesVisionParameters.fromJson(reader); + } else { + reader.skipChildren(); + } + } + if (nameFound) { + AIServicesVisionVectorizer deserializedAIServicesVisionVectorizer + = new AIServicesVisionVectorizer(name); + deserializedAIServicesVisionVectorizer.aIServicesVisionParameters = aIServicesVisionParameters; + + return deserializedAIServicesVisionVectorizer; + } + throw new IllegalStateException("Missing required property: name"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIStudioModelCatalogName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIStudioModelCatalogName.java new file mode 100644 index 0000000000000..a73552fdd6618 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIStudioModelCatalogName.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The name of the embedding model from the Azure AI Studio Catalog that will be called. + */ +public final class AIStudioModelCatalogName extends ExpandableStringEnum { + /** + * Static value OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32 for AIStudioModelCatalogName. + */ + public static final AIStudioModelCatalogName OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32 + = fromString("OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32"); + + /** + * Static value OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336 for AIStudioModelCatalogName. + */ + public static final AIStudioModelCatalogName OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VI_TLARGE_PATCH14336 + = fromString("OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336"); + + /** + * Static value Facebook-DinoV2-Image-Embeddings-ViT-Base for AIStudioModelCatalogName. + */ + public static final AIStudioModelCatalogName FACEBOOK_DINO_V2IMAGE_EMBEDDINGS_VI_TBASE + = fromString("Facebook-DinoV2-Image-Embeddings-ViT-Base"); + + /** + * Static value Facebook-DinoV2-Image-Embeddings-ViT-Giant for AIStudioModelCatalogName. + */ + public static final AIStudioModelCatalogName FACEBOOK_DINO_V2IMAGE_EMBEDDINGS_VI_TGIANT + = fromString("Facebook-DinoV2-Image-Embeddings-ViT-Giant"); + + /** + * Static value Cohere-embed-v3-english for AIStudioModelCatalogName. + */ + public static final AIStudioModelCatalogName COHERE_EMBED_V3ENGLISH = fromString("Cohere-embed-v3-english"); + + /** + * Static value Cohere-embed-v3-multilingual for AIStudioModelCatalogName. + */ + public static final AIStudioModelCatalogName COHERE_EMBED_V3MULTILINGUAL + = fromString("Cohere-embed-v3-multilingual"); + + /** + * Creates a new instance of AIStudioModelCatalogName value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AIStudioModelCatalogName() { + } + + /** + * Creates or finds a AIStudioModelCatalogName from its string representation. + * + * @param name a name to look for. + * @return the corresponding AIStudioModelCatalogName. + */ + public static AIStudioModelCatalogName fromString(String name) { + return fromString(name, AIStudioModelCatalogName.class); + } + + /** + * Gets known AIStudioModelCatalogName values. + * + * @return known AIStudioModelCatalogName values. + */ + public static Collection values() { + return values(AIStudioModelCatalogName.class); + } +} 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/AMLParameters.java new file mode 100644 index 0000000000000..bce09e0d1505d --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AMLParameters.java @@ -0,0 +1,248 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +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.implementation.CoreToCodegenBridgeUtils; +import java.io.IOException; +import java.time.Duration; + +/** + * Specifies the properties for connecting to an AML vectorizer. + */ +@Fluent +public final class AMLParameters 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. + */ + private final String scoringUri; + + /* + * (Required for key authentication) The key for the AML service. + */ + private String authenticationKey; + + /* + * (Required for token authentication). The Azure Resource Manager resource ID of the AML service. It should be in + * the format + * subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace + * -name}/services/{service_name}. + */ + private String resourceId; + + /* + * (Optional) When specified, indicates the timeout for the http client making the API call. + */ + private Duration timeout; + + /* + * (Optional for token authentication). The region the AML service is deployed in. + */ + private String region; + + /* + * The name of the embedding model from the Azure AI Studio Catalog that is deployed at the provided endpoint. + */ + private AIStudioModelCatalogName modelName; + + /** + * Creates an instance of AMLParameters class. + * + * @param scoringUri the scoringUri value to set. + */ + public AMLParameters(String scoringUri) { + this.scoringUri = scoringUri; + } + + /** + * Get the scoringUri property: (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. + * + * @return the scoringUri value. + */ + public String getScoringUri() { + return this.scoringUri; + } + + /** + * Get the authenticationKey property: (Required for key authentication) The key for the AML service. + * + * @return the authenticationKey value. + */ + public String getAuthenticationKey() { + return this.authenticationKey; + } + + /** + * 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. + */ + public AMLParameters setAuthenticationKey(String authenticationKey) { + this.authenticationKey = authenticationKey; + return this; + } + + /** + * Get the resourceId property: (Required for token authentication). The Azure Resource Manager resource ID of the + * AML service. It should be in the format + * subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.MachineLearningServices/workspaces/{workspace-name}/services/{service_name}. + * + * @return the resourceId value. + */ + public String getResourceId() { + return this.resourceId; + } + + /** + * Set the resourceId property: (Required for token authentication). The Azure Resource Manager resource ID of the + * AML service. It should be in the format + * 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. + */ + public AMLParameters setResourceId(String resourceId) { + this.resourceId = resourceId; + return this; + } + + /** + * Get the timeout property: (Optional) When specified, indicates the timeout for the http client making the API + * call. + * + * @return the timeout value. + */ + public Duration getTimeout() { + return this.timeout; + } + + /** + * Set the timeout property: (Optional) When specified, indicates the timeout for the http client making the API + * call. + * + * @param timeout the timeout value to set. + * @return the AMLParameters object itself. + */ + public AMLParameters setTimeout(Duration timeout) { + this.timeout = timeout; + return this; + } + + /** + * Get the region property: (Optional for token authentication). The region the AML service is deployed in. + * + * @return the region value. + */ + public String getRegion() { + return this.region; + } + + /** + * 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. + */ + public AMLParameters setRegion(String region) { + this.region = region; + return this; + } + + /** + * Get the modelName property: The name of the embedding model from the Azure AI Studio Catalog that is deployed at + * the provided endpoint. + * + * @return the modelName value. + */ + public AIStudioModelCatalogName getModelName() { + return this.modelName; + } + + /** + * Set the modelName property: The name of the embedding model from the Azure AI Studio Catalog that is deployed at + * the provided endpoint. + * + * @param modelName the modelName value to set. + * @return the AMLParameters object itself. + */ + public AMLParameters setModelName(AIStudioModelCatalogName modelName) { + this.modelName = modelName; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("uri", this.scoringUri); + jsonWriter.writeStringField("key", this.authenticationKey); + jsonWriter.writeStringField("resourceId", this.resourceId); + jsonWriter.writeStringField("timeout", CoreToCodegenBridgeUtils.durationToStringWithDays(this.timeout)); + jsonWriter.writeStringField("region", this.region); + jsonWriter.writeStringField("modelName", this.modelName == null ? null : this.modelName.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AMLParameters 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. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the AMLParameters. + */ + public static AMLParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean scoringUriFound = false; + String scoringUri = null; + String authenticationKey = null; + String resourceId = null; + Duration timeout = null; + String region = null; + AIStudioModelCatalogName modelName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("uri".equals(fieldName)) { + scoringUri = reader.getString(); + scoringUriFound = true; + } else if ("key".equals(fieldName)) { + authenticationKey = reader.getString(); + } else if ("resourceId".equals(fieldName)) { + resourceId = reader.getString(); + } else if ("timeout".equals(fieldName)) { + timeout = reader.getNullable(nonNullReader -> Duration.parse(nonNullReader.getString())); + } else if ("region".equals(fieldName)) { + region = reader.getString(); + } else if ("modelName".equals(fieldName)) { + modelName = AIStudioModelCatalogName.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + if (scoringUriFound) { + AMLParameters deserializedAMLParameters = new AMLParameters(scoringUri); + deserializedAMLParameters.authenticationKey = authenticationKey; + deserializedAMLParameters.resourceId = resourceId; + deserializedAMLParameters.timeout = timeout; + deserializedAMLParameters.region = region; + deserializedAMLParameters.modelName = modelName; + + return deserializedAMLParameters; + } + 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/AMLVectorizer.java new file mode 100644 index 0000000000000..505a34a8d9261 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AMLVectorizer.java @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Specifies an Azure Machine Learning endpoint deployed via the Azure AI Studio Model Catalog for generating the + * vector embedding of a query string. + */ +@Fluent +public final class AMLVectorizer extends VectorSearchVectorizer { + /* + * Specifies the properties of the AML vectorizer. + */ + private AMLParameters aMLParameters; + + /** + * Creates an instance of AMLVectorizer class. + * + * @param name the name value to set. + */ + public AMLVectorizer(String name) { + super(name); + } + + /** + * Get the aMLParameters property: Specifies the properties of the AML vectorizer. + * + * @return the aMLParameters value. + */ + public AMLParameters getAMLParameters() { + return this.aMLParameters; + } + + /** + * Set the aMLParameters property: Specifies the properties of the AML vectorizer. + * + * @param aMLParameters the aMLParameters value to set. + * @return the AMLVectorizer object itself. + */ + public AMLVectorizer setAMLParameters(AMLParameters aMLParameters) { + this.aMLParameters = aMLParameters; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kind", + VectorSearchVectorizerKind.AML == null ? null : VectorSearchVectorizerKind.AML.toString()); + jsonWriter.writeStringField("name", getName()); + jsonWriter.writeJsonField("amlParameters", this.aMLParameters); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AMLVectorizer 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. + * @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. + */ + public static AMLVectorizer fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean nameFound = false; + String name = null; + AMLParameters aMLParameters = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("kind".equals(fieldName)) { + String kind = reader.getString(); + if (!"aml".equals(kind)) { + throw new IllegalStateException( + "'kind' was expected to be non-null and equal to 'aml'. The found 'kind' was '" + kind + + "'."); + } + } else if ("name".equals(fieldName)) { + name = reader.getString(); + nameFound = true; + } else if ("amlParameters".equals(fieldName)) { + aMLParameters = AMLParameters.fromJson(reader); + } else { + reader.skipChildren(); + } + } + if (nameFound) { + AMLVectorizer deserializedAMLVectorizer = new AMLVectorizer(name); + deserializedAMLVectorizer.aMLParameters = aMLParameters; + + return deserializedAMLVectorizer; + } + throw new IllegalStateException("Missing required property: name"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIEmbeddingSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIEmbeddingSkill.java index c3be045c074d9..c1ed4c55ab13b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIEmbeddingSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIEmbeddingSkill.java @@ -20,17 +20,23 @@ @Fluent public final class AzureOpenAIEmbeddingSkill extends SearchIndexerSkill { /* - * The resource URI for your Azure OpenAI resource. + * The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and + * later models. + */ + private Integer dimensions; + + /* + * The resource URI of the Azure OpenAI resource. */ private String resourceUri; /* - * ID of your Azure OpenAI model deployment on the designated resource. + * ID of the Azure OpenAI model deployment on the designated resource. */ private String deploymentId; /* - * API key for the designated Azure OpenAI resource. + * API key of the designated Azure OpenAI resource. */ private String apiKey; @@ -39,6 +45,11 @@ public final class AzureOpenAIEmbeddingSkill extends SearchIndexerSkill { */ private SearchIndexerDataIdentity authIdentity; + /* + * The name of the embedding model that is deployed at the provided deploymentId path. + */ + private AzureOpenAIModelName modelName; + /** * Creates an instance of AzureOpenAIEmbeddingSkill class. * @@ -50,7 +61,29 @@ public AzureOpenAIEmbeddingSkill(List inputs, List { + /** + * Static value text-embedding-ada-002 for AzureOpenAIModelName. + */ + public static final AzureOpenAIModelName TEXT_EMBEDDING_ADA002 = fromString("text-embedding-ada-002"); + + /** + * Static value text-embedding-3-large for AzureOpenAIModelName. + */ + public static final AzureOpenAIModelName TEXT_EMBEDDING3LARGE = fromString("text-embedding-3-large"); + + /** + * Static value text-embedding-3-small for AzureOpenAIModelName. + */ + public static final AzureOpenAIModelName TEXT_EMBEDDING3SMALL = fromString("text-embedding-3-small"); + + /** + * Static value experimental for AzureOpenAIModelName. + */ + public static final AzureOpenAIModelName EXPERIMENTAL = fromString("experimental"); + + /** + * Creates a new instance of AzureOpenAIModelName value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureOpenAIModelName() { + } + + /** + * Creates or finds a AzureOpenAIModelName from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureOpenAIModelName. + */ + public static AzureOpenAIModelName fromString(String name) { + return fromString(name, AzureOpenAIModelName.class); + } + + /** + * Gets known AzureOpenAIModelName values. + * + * @return known AzureOpenAIModelName values. + */ + public static Collection values() { + return values(AzureOpenAIModelName.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIParameters.java index fb693158aca24..0f8b50ac10ef2 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIParameters.java @@ -17,7 +17,7 @@ * Specifies the parameters for connecting to the Azure OpenAI resource. */ @Fluent -public final class AzureOpenAIParameters implements JsonSerializable { +public class AzureOpenAIParameters implements JsonSerializable { /* * The resource URI of the Azure OpenAI resource. */ @@ -38,6 +38,11 @@ public final class AzureOpenAIParameters implements JsonSerializable { */ private String vectorSearchProfileName; + /* + * The encoding format to interpret the field contents. + */ + private VectorEncodingFormat vectorEncodingFormat; + /* * A list of the names of synonym maps to associate with this field. This option can be used only with searchable * fields. Currently only one synonym map per field is supported. Assigning a synonym map to a field ensures that @@ -543,6 +548,26 @@ public SearchField setVectorSearchProfileName(String vectorSearchProfileName) { return this; } + /** + * Get the vectorEncodingFormat property: The encoding format to interpret the field contents. + * + * @return the vectorEncodingFormat value. + */ + public VectorEncodingFormat getVectorEncodingFormat() { + return this.vectorEncodingFormat; + } + + /** + * Set the vectorEncodingFormat property: The encoding format to interpret the field contents. + * + * @param vectorEncodingFormat the vectorEncodingFormat value to set. + * @return the SearchField object itself. + */ + public SearchField setVectorEncodingFormat(VectorEncodingFormat vectorEncodingFormat) { + this.vectorEncodingFormat = vectorEncodingFormat; + return this; + } + /** * Get the synonymMapNames property: A list of the names of synonym maps to associate with this field. This option * can be used only with searchable fields. Currently only one synonym map per field is supported. Assigning a @@ -613,6 +638,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("normalizer", this.normalizerName == null ? null : this.normalizerName.toString()); jsonWriter.writeNumberField("dimensions", this.vectorSearchDimensions); jsonWriter.writeStringField("vectorSearchProfile", this.vectorSearchProfileName); + jsonWriter.writeStringField("vectorEncoding", + this.vectorEncodingFormat == null ? null : this.vectorEncodingFormat.toString()); jsonWriter.writeArrayField("synonymMaps", this.synonymMapNames, (writer, element) -> writer.writeString(element)); jsonWriter.writeArrayField("fields", this.fields, (writer, element) -> writer.writeJson(element)); @@ -647,6 +674,7 @@ public static SearchField fromJson(JsonReader jsonReader) throws IOException { LexicalNormalizerName normalizerName = null; Integer vectorSearchDimensions = null; String vectorSearchProfileName = null; + VectorEncodingFormat vectorEncodingFormat = null; List synonymMapNames = null; List fields = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -684,6 +712,8 @@ public static SearchField fromJson(JsonReader jsonReader) throws IOException { vectorSearchDimensions = reader.getNullable(JsonReader::getInt); } else if ("vectorSearchProfile".equals(fieldName)) { vectorSearchProfileName = reader.getString(); + } else if ("vectorEncoding".equals(fieldName)) { + vectorEncodingFormat = VectorEncodingFormat.fromString(reader.getString()); } else if ("synonymMaps".equals(fieldName)) { synonymMapNames = reader.readArray(reader1 -> reader1.getString()); } else if ("fields".equals(fieldName)) { @@ -707,6 +737,7 @@ public static SearchField fromJson(JsonReader jsonReader) throws IOException { deserializedSearchField.normalizerName = normalizerName; deserializedSearchField.vectorSearchDimensions = vectorSearchDimensions; deserializedSearchField.vectorSearchProfileName = vectorSearchProfileName; + deserializedSearchField.vectorEncodingFormat = vectorEncodingFormat; deserializedSearchField.synonymMapNames = synonymMapNames; deserializedSearchField.fields = fields; return deserializedSearchField; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchFieldDataType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchFieldDataType.java index cd4bfc06a1864..5932418c2a186 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchFieldDataType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchFieldDataType.java @@ -75,6 +75,11 @@ public final class SearchFieldDataType extends ExpandableStringEnum { + /* * The name of your Azure Key Vault key to be used to encrypt your data at rest. */ @@ -53,7 +53,7 @@ public final class SearchResourceEncryptionKey implements JsonSerializable missingProperties = new ArrayList<>(); @@ -187,7 +185,6 @@ public static SearchResourceEncryptionKey fromJson(JsonReader jsonReader) throws if (!vaultUrlFound) { missingProperties.add("keyVaultUri"); } - throw new IllegalStateException( "Missing required property/properties: " + String.join(", ", missingProperties)); }); @@ -197,7 +194,7 @@ public static SearchResourceEncryptionKey fromJson(JsonReader jsonReader) throws * Get the applicationId property: An AAD Application ID that was granted the required access permissions to the * Azure Key Vault that is to be used when encrypting your data at rest. The Application ID should not be confused * with the Object ID for your AAD Application. - * + * * @return the applicationId value. */ public String getApplicationId() { @@ -208,7 +205,7 @@ public String getApplicationId() { * Set the applicationId property: An AAD Application ID that was granted the required access permissions to the * Azure Key Vault that is to be used when encrypting your data at rest. The Application ID should not be confused * with the Object ID for your AAD Application. - * + * * @param applicationId the applicationId value to set. * @return the SearchResourceEncryptionKey object itself. */ @@ -216,14 +213,13 @@ public SearchResourceEncryptionKey setApplicationId(String applicationId) { if (this.accessCredentials == null) { this.accessCredentials = new AzureActiveDirectoryApplicationCredentials(); } - this.accessCredentials.setApplicationId(applicationId); return this; } /** * Get the applicationSecret property: The authentication key of the specified AAD application. - * + * * @return the applicationSecret value. */ public String getApplicationSecret() { @@ -232,7 +228,7 @@ public String getApplicationSecret() { /** * Set the applicationSecret property: The authentication key of the specified AAD application. - * + * * @param applicationSecret the applicationSecret value to set. * @return the SearchResourceEncryptionKey object itself. */ @@ -240,7 +236,6 @@ public SearchResourceEncryptionKey setApplicationSecret(String applicationSecret if (this.accessCredentials == null) { this.accessCredentials = new AzureActiveDirectoryApplicationCredentials(); } - this.accessCredentials.setApplicationSecret(applicationSecret); return this; } 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 0bf58d7577176..1a7bd1686be15 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 @@ -39,6 +39,11 @@ public final class SearchServiceLimits implements JsonSerializable { + /** + * Encoding format representing bits packed into a wider data type. + */ + public static final VectorEncodingFormat PACKED_BIT = fromString("packedBit"); + + /** + * Creates a new instance of VectorEncodingFormat value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public VectorEncodingFormat() { + } + + /** + * Creates or finds a VectorEncodingFormat from its string representation. + * + * @param name a name to look for. + * @return the corresponding VectorEncodingFormat. + */ + public static VectorEncodingFormat fromString(String name) { + return fromString(name, VectorEncodingFormat.class); + } + + /** + * Gets known VectorEncodingFormat values. + * + * @return known VectorEncodingFormat values. + */ + public static Collection values() { + return values(VectorEncodingFormat.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmMetric.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmMetric.java index 547612d0ae2c9..eaf0fd6e125a9 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmMetric.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmMetric.java @@ -10,24 +10,34 @@ import java.util.Collection; /** - * The similarity metric to use for vector comparisons. + * The similarity metric to use for vector comparisons. It is recommended to choose the same similarity metric as the + * embedding model was trained on. */ public final class VectorSearchAlgorithmMetric extends ExpandableStringEnum { /** - * Static value cosine for VectorSearchAlgorithmMetric. + * Measures the angle between vectors to quantify their similarity, disregarding magnitude. The smaller the angle, + * the closer the similarity. */ public static final VectorSearchAlgorithmMetric COSINE = fromString("cosine"); /** - * Static value euclidean for VectorSearchAlgorithmMetric. + * Computes the straight-line distance between vectors in a multi-dimensional space. The smaller the distance, the + * closer the similarity. */ public static final VectorSearchAlgorithmMetric EUCLIDEAN = fromString("euclidean"); /** - * Static value dotProduct for VectorSearchAlgorithmMetric. + * Calculates the sum of element-wise products to gauge alignment and magnitude similarity. The larger and more + * positive, the closer the similarity. */ public static final VectorSearchAlgorithmMetric DOT_PRODUCT = fromString("dotProduct"); + /** + * Only applicable to bit-packed binary data types. Determines dissimilarity by counting differing positions in + * binary vectors. The fewer differences, the closer the similarity. + */ + public static final VectorSearchAlgorithmMetric HAMMING = fromString("hamming"); + /** * Creates a new instance of VectorSearchAlgorithmMetric value. * 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 39ebfd11823da..092234212721c 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 @@ -79,6 +79,10 @@ public static VectorSearchVectorizer fromJson(JsonReader jsonReader) throws IOEx return AzureOpenAIVectorizer.fromJson(readerToUse.reset()); } else if ("customWebApi".equals(discriminatorValue)) { return CustomVectorizer.fromJson(readerToUse.reset()); + } else if ("aiServicesVision".equals(discriminatorValue)) { + return AIServicesVisionVectorizer.fromJson(readerToUse.reset()); + } else if ("aml".equals(discriminatorValue)) { + return AMLVectorizer.fromJson(readerToUse.reset()); } else { return fromJsonKnownDiscriminator(readerToUse.reset()); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizerKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizerKind.java index 70fda7d2384b9..6beb6f78b1059 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizerKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizerKind.java @@ -23,6 +23,17 @@ public final class VectorSearchVectorizerKind extends ExpandableStringEnum inputs, List outputs, + String modelVersion) { + super(inputs, outputs); + this.modelVersion = modelVersion; + } + + /** + * Get the modelVersion property: The version of the model to use when calling the AI Services Vision service. It + * will default to the latest available when not specified. + * + * @return the modelVersion value. + */ + public String getModelVersion() { + return this.modelVersion; + } + + /** + * {@inheritDoc} + */ + @Override + public VisionVectorizeSkill setName(String name) { + super.setName(name); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VisionVectorizeSkill setDescription(String description) { + super.setDescription(description); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VisionVectorizeSkill setContext(String context) { + super.setContext(context); + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("@odata.type", "#Microsoft.Skills.Vision.VectorizeSkill"); + jsonWriter.writeArrayField("inputs", getInputs(), (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("outputs", getOutputs(), (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("name", getName()); + jsonWriter.writeStringField("description", getDescription()); + jsonWriter.writeStringField("context", getContext()); + jsonWriter.writeStringField("modelVersion", this.modelVersion); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VisionVectorizeSkill from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VisionVectorizeSkill 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 VisionVectorizeSkill. + */ + public static VisionVectorizeSkill fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean inputsFound = false; + List inputs = null; + boolean outputsFound = false; + List outputs = null; + String name = null; + String description = null; + String context = null; + boolean modelVersionFound = false; + String modelVersion = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("@odata.type".equals(fieldName)) { + String odataType = reader.getString(); + if (!"#Microsoft.Skills.Vision.VectorizeSkill".equals(odataType)) { + throw new IllegalStateException( + "'@odata.type' was expected to be non-null and equal to '#Microsoft.Skills.Vision.VectorizeSkill'. The found '@odata.type' was '" + + odataType + "'."); + } + } else if ("inputs".equals(fieldName)) { + inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); + inputsFound = true; + } else if ("outputs".equals(fieldName)) { + outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); + outputsFound = true; + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else if ("context".equals(fieldName)) { + context = reader.getString(); + } else if ("modelVersion".equals(fieldName)) { + modelVersion = reader.getString(); + modelVersionFound = true; + } else { + reader.skipChildren(); + } + } + if (inputsFound && outputsFound && modelVersionFound) { + VisionVectorizeSkill deserializedVisionVectorizeSkill + = new VisionVectorizeSkill(inputs, outputs, modelVersion); + deserializedVisionVectorizeSkill.setName(name); + deserializedVisionVectorizeSkill.setDescription(description); + deserializedVisionVectorizeSkill.setContext(context); + + return deserializedVisionVectorizeSkill; + } + List missingProperties = new ArrayList<>(); + if (!inputsFound) { + missingProperties.add("inputs"); + } + if (!outputsFound) { + missingProperties.add("outputs"); + } + if (!modelVersionFound) { + missingProperties.add("modelVersion"); + } + + throw new IllegalStateException( + "Missing required property/properties: " + String.join(", ", missingProperties)); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridCountAndFacetMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridCountAndFacetMode.java new file mode 100644 index 0000000000000..303fe5ed8da58 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridCountAndFacetMode.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Determines whether the count and facets should includes all documents that matched the search query, or only the + * documents that are retrieved within the 'maxTextRecallSize' window. The default value is 'countAllResults'. + */ +public final class HybridCountAndFacetMode extends ExpandableStringEnum { + /** + * Only include documents that were matched within the 'maxTextRecallSize' retrieval window when computing 'count' + * and 'facets'. + */ + public static final HybridCountAndFacetMode COUNT_RETRIEVABLE_RESULTS = fromString("countRetrievableResults"); + + /** + * Include all documents that were matched by the search query when computing 'count' and 'facets', regardless of + * whether or not those documents are within the 'maxTextRecallSize' retrieval window. + */ + public static final HybridCountAndFacetMode COUNT_ALL_RESULTS = fromString("countAllResults"); + + /** + * Creates a new instance of HybridCountAndFacetMode value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public HybridCountAndFacetMode() { + } + + /** + * Creates or finds a HybridCountAndFacetMode from its string representation. + * + * @param name a name to look for. + * @return the corresponding HybridCountAndFacetMode. + */ + public static HybridCountAndFacetMode fromString(String name) { + return fromString(name, HybridCountAndFacetMode.class); + } + + /** + * Gets known HybridCountAndFacetMode values. + * + * @return known HybridCountAndFacetMode values. + */ + public static Collection values() { + return values(HybridCountAndFacetMode.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridSearch.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridSearch.java new file mode 100644 index 0000000000000..3d606d35ad8b6 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridSearch.java @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * TThe query parameters to configure hybrid search behaviors. + */ +@Fluent +public final class HybridSearch implements JsonSerializable { + /* + * Determines the maximum number of documents to be retrieved by the text query portion of a hybrid search request. + * Those documents will be combined with the documents matching the vector queries to produce a single final list + * of results. Choosing a larger maxTextRecallSize value will allow retrieving and paging through more documents + * (using the top and skip parameters), at the cost of higher resource utilization and higher latency. The value + * needs to be between 1 and 10,000. Default is 1000. + */ + private Integer maxTextRecallSize; + + /* + * Determines whether the count and facets should includes all documents that matched the search query, or only the + * documents that are retrieved within the 'maxTextRecallSize' window. + */ + private HybridCountAndFacetMode countAndFacetMode; + + /** + * Creates an instance of HybridSearch class. + */ + public HybridSearch() { + } + + /** + * Get the maxTextRecallSize property: Determines the maximum number of documents to be retrieved by the text query + * portion of a hybrid search request. Those documents will be combined with the documents matching the vector + * queries to produce a single final list of results. Choosing a larger maxTextRecallSize value will allow + * retrieving and paging through more documents (using the top and skip parameters), at the cost of higher resource + * utilization and higher latency. The value needs to be between 1 and 10,000. Default is 1000. + * + * @return the maxTextRecallSize value. + */ + public Integer getMaxTextRecallSize() { + return this.maxTextRecallSize; + } + + /** + * Set the maxTextRecallSize property: Determines the maximum number of documents to be retrieved by the text query + * portion of a hybrid search request. Those documents will be combined with the documents matching the vector + * queries to produce a single final list of results. Choosing a larger maxTextRecallSize value will allow + * retrieving and paging through more documents (using the top and skip parameters), at the cost of higher resource + * utilization and higher latency. The value needs to be between 1 and 10,000. Default is 1000. + * + * @param maxTextRecallSize the maxTextRecallSize value to set. + * @return the HybridSearch object itself. + */ + public HybridSearch setMaxTextRecallSize(Integer maxTextRecallSize) { + this.maxTextRecallSize = maxTextRecallSize; + return this; + } + + /** + * Get the countAndFacetMode property: Determines whether the count and facets should includes all documents that + * matched the search query, or only the documents that are retrieved within the 'maxTextRecallSize' window. + * + * @return the countAndFacetMode value. + */ + public HybridCountAndFacetMode getCountAndFacetMode() { + return this.countAndFacetMode; + } + + /** + * Set the countAndFacetMode property: Determines whether the count and facets should includes all documents that + * matched the search query, or only the documents that are retrieved within the 'maxTextRecallSize' window. + * + * @param countAndFacetMode the countAndFacetMode value to set. + * @return the HybridSearch object itself. + */ + public HybridSearch setCountAndFacetMode(HybridCountAndFacetMode countAndFacetMode) { + this.countAndFacetMode = countAndFacetMode; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("maxTextRecallSize", this.maxTextRecallSize); + jsonWriter.writeStringField("countAndFacetMode", + this.countAndFacetMode == null ? null : this.countAndFacetMode.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HybridSearch from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HybridSearch if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the HybridSearch. + */ + public static HybridSearch fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HybridSearch deserializedHybridSearch = new HybridSearch(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("maxTextRecallSize".equals(fieldName)) { + deserializedHybridSearch.maxTextRecallSize = reader.getNullable(JsonReader::getInt); + } else if ("countAndFacetMode".equals(fieldName)) { + deserializedHybridSearch.countAndFacetMode = HybridCountAndFacetMode.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedHybridSearch; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchOptions.java index b74214f6fc2f5..e20250916777d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchOptions.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchOptions.java @@ -161,6 +161,11 @@ public final class SearchOptions { private SemanticSearchOptions semanticSearchOptions; private VectorSearchOptions vectorSearchOptions; + /* + * The query parameters to configure hybrid search behaviors. + */ + private HybridSearch hybridSearch; + /** * Creates an instance of {@link SearchOptions}. */ @@ -668,4 +673,24 @@ public SearchOptions setVectorSearchOptions(VectorSearchOptions vectorSearchOpti public VectorSearchOptions getVectorSearchOptions() { return this.vectorSearchOptions; } + + /** + * Get the hybridSearch property: The query parameters to configure hybrid search behaviors. + * + * @return the hybridSearch value. + */ + public HybridSearch getHybridSearch() { + return this.hybridSearch; + } + + /** + * Set the hybridSearch property: The query parameters to configure hybrid search behaviors. + * + * @param hybridSearch the hybridSearch value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setHybridSearch(HybridSearch hybridSearch) { + this.hybridSearch = hybridSearch; + return this; + } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchScoreThreshold.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchScoreThreshold.java new file mode 100644 index 0000000000000..03b1f991afe8a --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchScoreThreshold.java @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +package com.azure.search.documents.models; + +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * The results of the vector query will filter based on the '@search.score' value. Note this is the @search.score + * returned as part of the search response. The threshold direction will be chosen for higher @search.score. + */ +@Immutable +public final class SearchScoreThreshold extends VectorThreshold { + + /* + * The threshold will filter based on the '@search.score' value. Note this is the @search.score returned as part of + * the search response. The threshold direction will be chosen for higher @search.score. + */ + private final double value; + + /** + * Creates an instance of SearchScoreThreshold class. + * + * @param value the value value to set. + */ + public SearchScoreThreshold(double value) { + this.value = value; + } + + /** + * /** + * Get the value property: The threshold will filter based on the '@search.score' value. Note this is the + * + * `@search.score` returned as part of the search response. The threshold direction will be chosen for higher + * `@search.score`. + * + * @return the value. + * / + */ + public double getValue() { + return this.value; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kind", + VectorThresholdKind.SEARCH_SCORE == null ? null : VectorThresholdKind.SEARCH_SCORE.toString()); + jsonWriter.writeDoubleField("value", this.value); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SearchScoreThreshold from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SearchScoreThreshold 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 SearchScoreThreshold. + */ + public static SearchScoreThreshold fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean valueFound = false; + double value = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("kind".equals(fieldName)) { + String kind = reader.getString(); + if (!"searchScore".equals(kind)) { + throw new IllegalStateException( + "'kind' was expected to be non-null and equal to 'searchScore'. The found 'kind' was '" + + kind + "'."); + } + } else if ("value".equals(fieldName)) { + value = reader.getDouble(); + valueFound = true; + } else { + reader.skipChildren(); + } + } + if (valueFound) { + return new SearchScoreThreshold(value); + } + throw new IllegalStateException("Missing required property: value"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java index 17e5acba8ef50..054fb56fe4f84 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java @@ -41,6 +41,20 @@ public class VectorQuery implements JsonSerializable { */ private Double oversampling; + /* + * Relative weight of the vector query when compared to other vector query and/or the text query within the same + * search request. This value is used when combining the results of multiple ranking lists produced by the + * different vector queries and/or the results retrieved through the text query. The higher the weight, the higher + * the documents that matched that query will be in the final ranking. Default is 1.0 and the value needs to be a + * positive number larger than zero. + */ + private Float weight; + + /* + * The threshold used for vector queries. Note this can only be set if all 'fields' use the same similarity metric. + */ + private VectorThreshold threshold; + /** * Creates an instance of VectorQuery class. */ @@ -135,6 +149,56 @@ public VectorQuery setOversampling(Double oversampling) { return this; } + /** + * Get the weight property: Relative weight of the vector query when compared to other vector query and/or the text + * query within the same search request. This value is used when combining the results of multiple ranking lists + * produced by the different vector queries and/or the results retrieved through the text query. The higher the + * weight, the higher the documents that matched that query will be in the final ranking. Default is 1.0 and the + * value needs to be a positive number larger than zero. + * + * @return the weight value. + */ + public Float getWeight() { + return this.weight; + } + + /** + * Set the weight property: Relative weight of the vector query when compared to other vector query and/or the text + * query within the same search request. This value is used when combining the results of multiple ranking lists + * produced by the different vector queries and/or the results retrieved through the text query. The higher the + * weight, the higher the documents that matched that query will be in the final ranking. Default is 1.0 and the + * value needs to be a positive number larger than zero. + * + * @param weight the weight value to set. + * @return the VectorQuery object itself. + */ + public VectorQuery setWeight(Float weight) { + this.weight = weight; + return this; + } + + /** + * Get the threshold property: The threshold used for vector queries. Note this can only be set if all 'fields' use + * the same similarity metric. + * + * @return the threshold value. + */ + public VectorThreshold getThreshold() { + return this.threshold; + } + + /** + * Set the threshold property: The threshold used for vector queries. Note this can only be set if all 'fields' use + * the same similarity metric. + * + * @param threshold the threshold value to set. + * @return the VectorQuery object itself. + */ + public VectorQuery setThreshold(VectorThreshold threshold) { + this.threshold = threshold; + return this; + } + @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -142,6 +206,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("fields", this.fields); jsonWriter.writeBooleanField("exhaustive", this.exhaustive); jsonWriter.writeNumberField("oversampling", this.oversampling); + jsonWriter.writeNumberField("weight", this.weight); + jsonWriter.writeJsonField("threshold", this.threshold); return jsonWriter.writeEndObject(); } @@ -173,6 +239,10 @@ public static VectorQuery fromJson(JsonReader jsonReader) throws IOException { // Use the discriminator value to determine which subtype should be deserialized. if ("text".equals(discriminatorValue)) { return VectorizableTextQuery.fromJson(readerToUse.reset()); + } else if ("imageUrl".equals(discriminatorValue)) { + return VectorizableImageUrlQuery.fromJson(readerToUse.reset()); + } else if ("imageBinary".equals(discriminatorValue)) { + return VectorizableImageBinaryQuery.fromJson(readerToUse.reset()); } else if ("vector".equals(discriminatorValue)) { return VectorizedQuery.fromJson(readerToUse.reset()); } else { @@ -195,6 +265,10 @@ static VectorQuery fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx deserializedVectorQuery.exhaustive = reader.getNullable(JsonReader::getBoolean); } else if ("oversampling".equals(fieldName)) { deserializedVectorQuery.oversampling = reader.getNullable(JsonReader::getDouble); + } else if ("weight".equals(fieldName)) { + deserializedVectorQuery.weight = reader.getNullable(JsonReader::getFloat); + } else if ("threshold".equals(fieldName)) { + deserializedVectorQuery.threshold = VectorThreshold.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSimilarityThreshold.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSimilarityThreshold.java new file mode 100644 index 0000000000000..87d77c75b63d7 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSimilarityThreshold.java @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * The results of the vector query will be filtered based on the vector similarity metric. Note this is the canonical + * definition of similarity metric, not the 'distance' version. The threshold direction (larger or smaller) will be + * chosen automatically according to the metric used by the field. + */ +@Immutable +public final class VectorSimilarityThreshold extends VectorThreshold { + /* + * The threshold will filter based on the similarity metric value. Note this is the canonical definition of + * similarity metric, not the 'distance' version. The threshold direction (larger or smaller) will be chosen + * automatically according to the metric used by the field. + */ + private final double value; + + /** + * Creates an instance of VectorSimilarityThreshold class. + * + * @param value the value value to set. + */ + public VectorSimilarityThreshold(double value) { + this.value = value; + } + + /** + * Get the value property: The threshold will filter based on the similarity metric value. Note this is the + * canonical definition of similarity metric, not the 'distance' version. The threshold direction (larger or + * smaller) will be chosen automatically according to the metric used by the field. + * + * @return the value value. + */ + public double getValue() { + return this.value; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kind", + VectorThresholdKind.VECTOR_SIMILARITY == null ? null : VectorThresholdKind.VECTOR_SIMILARITY.toString()); + jsonWriter.writeDoubleField("value", this.value); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VectorSimilarityThreshold from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VectorSimilarityThreshold 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 VectorSimilarityThreshold. + */ + public static VectorSimilarityThreshold fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean valueFound = false; + double value = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("kind".equals(fieldName)) { + String kind = reader.getString(); + if (!"vectorSimilarity".equals(kind)) { + throw new IllegalStateException( + "'kind' was expected to be non-null and equal to 'vectorSimilarity'. The found 'kind' was '" + + kind + "'."); + } + } else if ("value".equals(fieldName)) { + value = reader.getDouble(); + valueFound = true; + } else { + reader.skipChildren(); + } + } + if (valueFound) { + return new VectorSimilarityThreshold(value); + } + throw new IllegalStateException("Missing required property: value"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThreshold.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThreshold.java new file mode 100644 index 0000000000000..275649bc43243 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThreshold.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * The threshold used for vector queries. + */ +@Immutable +public class VectorThreshold implements JsonSerializable { + /** + * Creates an instance of VectorThreshold class. + */ + public VectorThreshold() { + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VectorThreshold from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VectorThreshold 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 the polymorphic discriminator. + * @throws IOException If an error occurs while reading the VectorThreshold. + */ + public static VectorThreshold fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + JsonReader readerToUse = reader.bufferObject(); + + readerToUse.nextToken(); // Prepare for reading + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("kind".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("vectorSimilarity".equals(discriminatorValue)) { + return VectorSimilarityThreshold.fromJson(readerToUse.reset()); + } else if ("searchScore".equals(discriminatorValue)) { + return SearchScoreThreshold.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + }); + } + + static VectorThreshold fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VectorThreshold deserializedVectorThreshold = new VectorThreshold(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + reader.skipChildren(); + } + + return deserializedVectorThreshold; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThresholdKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThresholdKind.java new file mode 100644 index 0000000000000..7e33bb0a8ea39 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThresholdKind.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The kind of vector query being performed. + */ +public final class VectorThresholdKind extends ExpandableStringEnum { + /** + * The results of the vector query will be filtered based on the vector similarity metric. Note this is the + * canonical definition of similarity metric, not the 'distance' version. The threshold direction (larger or + * smaller) will be chosen automatically according to the metric used by the field. + */ + public static final VectorThresholdKind VECTOR_SIMILARITY = fromString("vectorSimilarity"); + + /** + * The results of the vector query will filter based on the '@search.score' value. Note this is the @search.score + * returned as part of the search response. The threshold direction will be chosen for higher @search.score. + */ + public static final VectorThresholdKind SEARCH_SCORE = fromString("searchScore"); + + /** + * Creates a new instance of VectorThresholdKind value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public VectorThresholdKind() { + } + + /** + * Creates or finds a VectorThresholdKind from its string representation. + * + * @param name a name to look for. + * @return the corresponding VectorThresholdKind. + */ + public static VectorThresholdKind fromString(String name) { + return fromString(name, VectorThresholdKind.class); + } + + /** + * Gets known VectorThresholdKind values. + * + * @return known VectorThresholdKind values. + */ + public static Collection values() { + return values(VectorThresholdKind.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java new file mode 100644 index 0000000000000..812ea943f84fa --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +package com.azure.search.documents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.search.documents.implementation.models.VectorQueryKind; +import java.io.IOException; + +/** + * The query parameters to use for vector search when a base 64 encoded binary of an image that needs to be vectorized + * is provided. + */ +@Fluent +public final class VectorizableImageBinaryQuery extends VectorQuery { + + /* + * The base 64 encoded binary of an image to be vectorized to perform a vector search query. + */ + private String base64Image; + + /** + * Creates an instance of VectorizableImageBinaryQuery class. + */ + public VectorizableImageBinaryQuery() { + } + + /** + * Get the base64Image property: The base 64 encoded binary of an image to be vectorized to perform a vector search + * query. + * + * @return the base64Image value. + */ + public String getBase64Image() { + return this.base64Image; + } + + /** + * Set the base64Image property: The base 64 encoded binary of an image to be vectorized to perform a vector search + * query. + * + * @param base64Image the base64Image value to set. + * @return the VectorizableImageBinaryQuery object itself. + */ + public VectorizableImageBinaryQuery setBase64Image(String base64Image) { + this.base64Image = base64Image; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageBinaryQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) { + super.setKNearestNeighborsCount(kNearestNeighborsCount); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageBinaryQuery setFields(String... fields) { + super.setFields(fields); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageBinaryQuery setExhaustive(Boolean exhaustive) { + super.setExhaustive(exhaustive); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageBinaryQuery setOversampling(Double oversampling) { + super.setOversampling(oversampling); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageBinaryQuery setWeight(Float weight) { + super.setWeight(weight); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageBinaryQuery setThreshold(VectorThreshold threshold) { + super.setThreshold(threshold); + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kind", + VectorQueryKind.IMAGE_BINARY == null ? null : VectorQueryKind.IMAGE_BINARY.toString()); + jsonWriter.writeNumberField("k", getKNearestNeighborsCount()); + jsonWriter.writeStringField("fields", getFields()); + jsonWriter.writeBooleanField("exhaustive", isExhaustive()); + jsonWriter.writeNumberField("oversampling", getOversampling()); + jsonWriter.writeNumberField("weight", getWeight()); + jsonWriter.writeJsonField("threshold", getThreshold()); + jsonWriter.writeStringField("base64Image", this.base64Image); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VectorizableImageBinaryQuery from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VectorizableImageBinaryQuery 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 the polymorphic discriminator. + * @throws IOException If an error occurs while reading the VectorizableImageBinaryQuery. + */ + public static VectorizableImageBinaryQuery fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VectorizableImageBinaryQuery deserializedVectorizableImageBinaryQuery = new VectorizableImageBinaryQuery(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("kind".equals(fieldName)) { + String kind = reader.getString(); + if (!"imageBinary".equals(kind)) { + throw new IllegalStateException( + "'kind' was expected to be non-null and equal to 'imageBinary'. The found 'kind' was '" + + kind + "'."); + } + } else if ("k".equals(fieldName)) { + deserializedVectorizableImageBinaryQuery + .setKNearestNeighborsCount(reader.getNullable(JsonReader::getInt)); + } else if ("fields".equals(fieldName)) { + deserializedVectorizableImageBinaryQuery.setFields(reader.getString()); + } else if ("exhaustive".equals(fieldName)) { + deserializedVectorizableImageBinaryQuery.setExhaustive(reader.getNullable(JsonReader::getBoolean)); + } else if ("oversampling".equals(fieldName)) { + deserializedVectorizableImageBinaryQuery.setOversampling(reader.getNullable(JsonReader::getDouble)); + } else if ("weight".equals(fieldName)) { + deserializedVectorizableImageBinaryQuery.setWeight(reader.getNullable(JsonReader::getFloat)); + } else if ("threshold".equals(fieldName)) { + deserializedVectorizableImageBinaryQuery.setThreshold(VectorThreshold.fromJson(reader)); + } else if ("base64Image".equals(fieldName)) { + deserializedVectorizableImageBinaryQuery.base64Image = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedVectorizableImageBinaryQuery; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java new file mode 100644 index 0000000000000..a9616bcf36577 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +package com.azure.search.documents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.search.documents.implementation.models.VectorQueryKind; +import java.io.IOException; + +/** + * The query parameters to use for vector search when an url that represents an image value that needs to be vectorized + * is provided. + */ +@Fluent +public final class VectorizableImageUrlQuery extends VectorQuery { + + /* + * The URL of an image to be vectorized to perform a vector search query. + */ + private String url; + + /** + * Creates an instance of VectorizableImageUrlQuery class. + */ + public VectorizableImageUrlQuery() { + } + + /** + * Get the url property: The URL of an image to be vectorized to perform a vector search query. + * + * @return the url value. + */ + public String getUrl() { + return this.url; + } + + /** + * Set the url property: The URL of an image to be vectorized to perform a vector search query. + * + * @param url the url value to set. + * @return the VectorizableImageUrlQuery object itself. + */ + public VectorizableImageUrlQuery setUrl(String url) { + this.url = url; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageUrlQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) { + super.setKNearestNeighborsCount(kNearestNeighborsCount); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageUrlQuery setFields(String... fields) { + super.setFields(fields); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageUrlQuery setExhaustive(Boolean exhaustive) { + super.setExhaustive(exhaustive); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageUrlQuery setOversampling(Double oversampling) { + super.setOversampling(oversampling); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageUrlQuery setWeight(Float weight) { + super.setWeight(weight); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageUrlQuery setThreshold(VectorThreshold threshold) { + super.setThreshold(threshold); + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kind", + VectorQueryKind.IMAGE_URL == null ? null : VectorQueryKind.IMAGE_URL.toString()); + jsonWriter.writeNumberField("k", getKNearestNeighborsCount()); + jsonWriter.writeStringField("fields", getFields()); + jsonWriter.writeBooleanField("exhaustive", isExhaustive()); + jsonWriter.writeNumberField("oversampling", getOversampling()); + jsonWriter.writeNumberField("weight", getWeight()); + jsonWriter.writeJsonField("threshold", getThreshold()); + jsonWriter.writeStringField("url", this.url); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VectorizableImageUrlQuery from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VectorizableImageUrlQuery 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 the polymorphic discriminator. + * @throws IOException If an error occurs while reading the VectorizableImageUrlQuery. + */ + public static VectorizableImageUrlQuery fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VectorizableImageUrlQuery deserializedVectorizableImageUrlQuery = new VectorizableImageUrlQuery(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("kind".equals(fieldName)) { + String kind = reader.getString(); + if (!"imageUrl".equals(kind)) { + throw new IllegalStateException( + "'kind' was expected to be non-null and equal to 'imageUrl'. The found 'kind' was '" + kind + + "'."); + } + } else if ("k".equals(fieldName)) { + deserializedVectorizableImageUrlQuery + .setKNearestNeighborsCount(reader.getNullable(JsonReader::getInt)); + } else if ("fields".equals(fieldName)) { + deserializedVectorizableImageUrlQuery.setFields(reader.getString()); + } else if ("exhaustive".equals(fieldName)) { + deserializedVectorizableImageUrlQuery.setExhaustive(reader.getNullable(JsonReader::getBoolean)); + } else if ("oversampling".equals(fieldName)) { + deserializedVectorizableImageUrlQuery.setOversampling(reader.getNullable(JsonReader::getDouble)); + } else if ("weight".equals(fieldName)) { + deserializedVectorizableImageUrlQuery.setWeight(reader.getNullable(JsonReader::getFloat)); + } else if ("threshold".equals(fieldName)) { + deserializedVectorizableImageUrlQuery.setThreshold(VectorThreshold.fromJson(reader)); + } else if ("url".equals(fieldName)) { + deserializedVectorizableImageUrlQuery.url = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedVectorizableImageUrlQuery; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java index b9be6cf439a8d..36650886eab81 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java @@ -77,6 +77,24 @@ public VectorizableTextQuery setOversampling(Double oversampling) { return this; } + /** + * {@inheritDoc} + */ + @Override + public VectorizableTextQuery setWeight(Float weight) { + super.setWeight(weight); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizableTextQuery setThreshold(VectorThreshold threshold) { + super.setThreshold(threshold); + return this; + } + @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -85,6 +103,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("fields", getFields()); jsonWriter.writeBooleanField("exhaustive", isExhaustive()); jsonWriter.writeNumberField("oversampling", getOversampling()); + jsonWriter.writeNumberField("weight", getWeight()); + jsonWriter.writeJsonField("threshold", getThreshold()); jsonWriter.writeStringField("text", this.text); return jsonWriter.writeEndObject(); } @@ -105,6 +125,8 @@ public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOExc String fields = null; Boolean exhaustive = null; Double oversampling = null; + Float weight = null; + VectorThreshold threshold = null; boolean textFound = false; String text = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -125,6 +147,10 @@ public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOExc exhaustive = reader.getNullable(JsonReader::getBoolean); } else if ("oversampling".equals(fieldName)) { oversampling = reader.getNullable(JsonReader::getDouble); + } else if ("weight".equals(fieldName)) { + weight = reader.getNullable(JsonReader::getFloat); + } else if ("threshold".equals(fieldName)) { + threshold = VectorThreshold.fromJson(reader); } else if ("text".equals(fieldName)) { text = reader.getString(); textFound = true; @@ -138,6 +164,8 @@ public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOExc deserializedVectorizableTextQuery.setFields(fields); deserializedVectorizableTextQuery.setExhaustive(exhaustive); deserializedVectorizableTextQuery.setOversampling(oversampling); + deserializedVectorizableTextQuery.setWeight(weight); + deserializedVectorizableTextQuery.setThreshold(threshold); return deserializedVectorizableTextQuery; } throw new IllegalStateException("Missing required property: text"); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java index b523b504ccd87..9bb6b9a906779 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java @@ -78,6 +78,24 @@ public VectorizedQuery setOversampling(Double oversampling) { return this; } + /** + * {@inheritDoc} + */ + @Override + public VectorizedQuery setWeight(Float weight) { + super.setWeight(weight); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public VectorizedQuery setThreshold(VectorThreshold threshold) { + super.setThreshold(threshold); + return this; + } + @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -86,6 +104,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("fields", getFields()); jsonWriter.writeBooleanField("exhaustive", isExhaustive()); jsonWriter.writeNumberField("oversampling", getOversampling()); + jsonWriter.writeNumberField("weight", getWeight()); + jsonWriter.writeJsonField("threshold", getThreshold()); jsonWriter.writeArrayField("vector", this.vector, (writer, element) -> writer.writeFloat(element)); return jsonWriter.writeEndObject(); } @@ -106,6 +126,8 @@ public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException String fields = null; Boolean exhaustive = null; Double oversampling = null; + Float weight = null; + VectorThreshold threshold = null; boolean vectorFound = false; List vector = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -126,6 +148,10 @@ public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException exhaustive = reader.getNullable(JsonReader::getBoolean); } else if ("oversampling".equals(fieldName)) { oversampling = reader.getNullable(JsonReader::getDouble); + } else if ("weight".equals(fieldName)) { + weight = reader.getNullable(JsonReader::getFloat); + } else if ("threshold".equals(fieldName)) { + threshold = VectorThreshold.fromJson(reader); } else if ("vector".equals(fieldName)) { vector = reader.readArray(reader1 -> reader1.getFloat()); vectorFound = true; @@ -139,6 +165,8 @@ public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException deserializedVectorizedQuery.setFields(fields); deserializedVectorizedQuery.setExhaustive(exhaustive); deserializedVectorizedQuery.setOversampling(oversampling); + deserializedVectorizedQuery.setWeight(weight); + deserializedVectorizedQuery.setThreshold(threshold); return deserializedVectorizedQuery; } throw new IllegalStateException("Missing required property: vector"); diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientJavaDocSnippets.java index 7467a496e4cfb..00a3b5a83e6c8 100644 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientJavaDocSnippets.java +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientJavaDocSnippets.java @@ -21,7 +21,7 @@ public class SearchClientJavaDocSnippets { private static SearchClient searchClient; - private static SearchClient createSearchClientWithSearcClientBuilder() { + private static SearchClient createSearchClientWithSearchClientBuilder() { // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.instantiationWithSearchClientBuilder SearchClient searchClient = new SearchClientBuilder() .credential(new AzureKeyCredential("{key}")) @@ -36,7 +36,7 @@ private static SearchClient createSearchClientWithSearcClientBuilder() { * Uploading a document to a SearchClient index. */ public static void uploadDocument() { - searchClient = createSearchClientWithSearcClientBuilder(); + searchClient = createSearchClientWithSearchClientBuilder(); // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.uploadDocument#Map-boolean List hotels = new ArrayList<>(); hotels.add(new Hotel().setHotelId("100")); @@ -50,7 +50,7 @@ public static void uploadDocument() { * Merge a document in a SearchClient index. */ public static void mergeDocument() { - searchClient = createSearchClientWithSearcClientBuilder(); + searchClient = createSearchClientWithSearchClientBuilder(); // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.mergeDocument#Map List hotels = new ArrayList<>(); hotels.add(new Hotel().setHotelId("100")); @@ -63,7 +63,7 @@ public static void mergeDocument() { * Delete a document in a SearchClient index. */ public static void deleteDocument() { - searchClient = createSearchClientWithSearcClientBuilder(); + searchClient = createSearchClientWithSearchClientBuilder(); // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.deleteDocument#String SearchDocument documentId = new SearchDocument(); documentId.put("hotelId", "100"); @@ -75,7 +75,7 @@ public static void deleteDocument() { * Retrieve a document from a SearchClient index. */ public static void getDocument() { - searchClient = createSearchClientWithSearcClientBuilder(); + searchClient = createSearchClientWithSearchClientBuilder(); // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.getDocument#String-Class Hotel hotel = searchClient.getDocument("100", Hotel.class); System.out.printf("Retrieved Hotel %s%n", hotel.getHotelId()); @@ -86,7 +86,7 @@ public static void getDocument() { * Search documents in a SearchClient index. */ public static void searchDocuments() { - searchClient = createSearchClientWithSearcClientBuilder(); + searchClient = createSearchClientWithSearchClientBuilder(); // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.searchDocuments#String SearchDocument searchDocument = new SearchDocument(); searchDocument.put("hotelId", "8"); @@ -112,7 +112,7 @@ public static void searchDocuments() { * Make a suggestion query to a SearchClient index. */ public static void suggestDocuments() { - searchClient = createSearchClientWithSearcClientBuilder(); + searchClient = createSearchClientWithSearchClientBuilder(); // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.suggestDocuments#String-String SuggestPagedIterable suggestPagedIterable = searchClient.suggest("searchText", "sg"); for (SuggestResult result: suggestPagedIterable) { @@ -125,7 +125,7 @@ public static void suggestDocuments() { * Autocomplete a query in a SearchClient index. */ public static void autocompleteDocuments() { - searchClient = createSearchClientWithSearcClientBuilder(); + searchClient = createSearchClientWithSearchClientBuilder(); // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.autocomplete#String-String AutocompletePagedIterable autocompletePagedIterable = searchClient.autocomplete("searchText", "sg"); for (AutocompleteItem result: autocompletePagedIterable) { diff --git a/sdk/search/azure-search-documents/swagger/README.md b/sdk/search/azure-search-documents/swagger/README.md index faac14825de7a..9be65913d5023 100644 --- a/sdk/search/azure-search-documents/swagger/README.md +++ b/sdk/search/azure-search-documents/swagger/README.md @@ -87,7 +87,7 @@ These settings apply only when `--tag=searchindex` is specified on the command l ``` yaml $(tag) == 'searchindex' namespace: com.azure.search.documents input-file: -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/a0151afd7cd14913fc86cb793bde49c71122eb1e/specification/search/data-plane/Azure.Search/preview/2024-03-01-Preview/searchindex.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/5a1fe448805429403c38a2637ee32c82ba755530/specification/search/data-plane/Azure.Search/preview/2024-05-01-preview/searchindex.json models-subpackage: models custom-types-subpackage: implementation.models custom-types: AutocompleteRequest,IndexAction,IndexBatch,RequestOptions,SearchDocumentsResult,SearchErrorException,SearchOptions,SearchRequest,SearchResult,SuggestDocumentsResult,SuggestRequest,SuggestResult,VectorQueryKind,ErrorAdditionalInfo,ErrorDetail,ErrorResponse,ErrorResponseException,ScalarQuantizationParameters,ScalarQuantizationCompressionConfiguration @@ -105,7 +105,7 @@ These settings apply only when `--tag=searchservice` is specified on the command ``` yaml $(tag) == 'searchservice' namespace: com.azure.search.documents.indexes input-file: -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/a0151afd7cd14913fc86cb793bde49c71122eb1e/specification/search/data-plane/Azure.Search/preview/2024-03-01-Preview/searchservice.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/5a1fe448805429403c38a2637ee32c82ba755530/specification/search/data-plane/Azure.Search/preview/2024-05-01-preview/searchservice.json models-subpackage: models custom-types-subpackage: implementation.models custom-types: AnalyzeRequest,AnalyzeResult,AzureActiveDirectoryApplicationCredentials,DataSourceCredentials,DocumentKeysOrIds,EdgeNGramTokenFilterV1,EdgeNGramTokenFilterV2,EntityRecognitionSkillV1,EntityRecognitionSkillV3,KeywordTokenizerV1,KeywordTokenizerV2,ListAliasesResult,ListDataSourcesResult,ListIndexersResult,ListIndexesResult,ListSkillsetsResult,ListSynonymMapsResult,LuceneStandardTokenizerV1,LuceneStandardTokenizerV2,NGramTokenFilterV1,NGramTokenFilterV2,RequestOptions,SearchErrorException,SentimentSkillV1,SentimentSkillV3,SkillNames,VectorSearchAlgorithmKind,ErrorAdditionalInfo,ErrorDetail,ErrorResponse,ErrorResponseException,ScalarQuantizationParameters,ScalarQuantizationCompressionConfiguration @@ -216,6 +216,30 @@ 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' +directive: + - from: swagger-document + where: $.definitions.SearchRequest.properties + transform: > + delete $.hybridSearch["type"]; + delete $.hybridSearch.items; + $.hybridSearch["$ref"] = "#/definitions/HybridSearch"; + +``` + ### Remove required from properties that are optional ``` yaml $(tag) == 'searchservice' diff --git a/sdk/search/azure-search-documents/swagger/Update-Codegeneration-DISABLED.ps1 b/sdk/search/azure-search-documents/swagger/Update-Codegeneration.ps1 similarity index 100% rename from sdk/search/azure-search-documents/swagger/Update-Codegeneration-DISABLED.ps1 rename to sdk/search/azure-search-documents/swagger/Update-Codegeneration.ps1 diff --git a/sdk/search/azure-search-documents/swagger/src/main/java/SearchIndexCustomizations.java b/sdk/search/azure-search-documents/swagger/src/main/java/SearchIndexCustomizations.java index 0e98334d48715..b612c668b797c 100644 --- a/sdk/search/azure-search-documents/swagger/src/main/java/SearchIndexCustomizations.java +++ b/sdk/search/azure-search-documents/swagger/src/main/java/SearchIndexCustomizations.java @@ -3,6 +3,7 @@ import com.azure.autorest.customization.ClassCustomization; import com.azure.autorest.customization.Customization; +import com.azure.autorest.customization.JavadocCustomization; import com.azure.autorest.customization.LibraryCustomization; import com.azure.autorest.customization.PackageCustomization; import com.github.javaparser.StaticJavaParser; @@ -79,6 +80,9 @@ private void customizeModelsPackage(PackageCustomization packageCustomization) { customizeVectorQuery(packageCustomization.getClass("VectorQuery")); customizeVectorizedQuery(packageCustomization.getClass("VectorizedQuery")); customizeVectorizableTextQuery(packageCustomization.getClass("VectorizableTextQuery")); + customizeVectorizableImageUrlQuery(packageCustomization.getClass("VectorizableImageUrlQuery")); + customizeVectorizableImageBinaryQuery(packageCustomization.getClass("VectorizableImageBinaryQuery")); + customizeSearchScoreThreshold(packageCustomization.getClass("SearchScoreThreshold")); packageCustomization.getClass("QueryAnswerResult").removeMethod("setAdditionalProperties"); packageCustomization.getClass("QueryCaptionResult").removeMethod("setAdditionalProperties"); @@ -243,6 +247,39 @@ private void customizeSearchError(ClassCustomization classCustomization) { }); } + private void customizeVectorizableImageUrlQuery(ClassCustomization classCustomization) { + customizeAst(classCustomization, clazz -> clazz.getMethodsByName("setFields").get(0) + .setParameters(new NodeList<>(new Parameter().setType("String").setName("fields").setVarArgs(true))) + .setBody(StaticJavaParser.parseBlock("{\n" + + " super.setFields(fields);\n" + + " return this;\n" + + " }"))); + } + + private void customizeVectorizableImageBinaryQuery(ClassCustomization classCustomization) { + customizeAst(classCustomization, clazz -> clazz.getMethodsByName("setFields").get(0) + .setParameters(new NodeList<>(new Parameter().setType("String").setName("fields").setVarArgs(true))) + .setBody(StaticJavaParser.parseBlock("{\n" + + " super.setFields(fields);\n" + + " return this;\n" + + " }"))); + } + + private void customizeSearchScoreThreshold(ClassCustomization classCustomization) { + customizeAst(classCustomization, clazz -> { + clazz.getMethodsByName("getValue").get(0).setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( + "/**", + " * Get the value property: The threshold will filter based on the '@search.score' value. Note this is the", + " *", + " * `@search.score` returned as part of the search response. The threshold direction will be chosen for higher", + " * `@search.score`.", + " *", + " * @return the value.", + " */" + ))); + }); + } + private static void customizeAst(ClassCustomization classCustomization, Consumer consumer) { classCustomization.customizeAst(ast -> consumer.accept(ast.getClassByName(classCustomization.getClassName()) .orElseThrow(() -> new RuntimeException("Class not found. " + classCustomization.getClassName())))); diff --git a/sdk/search/azure-search-documents/swagger/src/main/java/SearchServiceCustomizations.java b/sdk/search/azure-search-documents/swagger/src/main/java/SearchServiceCustomizations.java index e2cbe06d9f04f..dcd3d4d8c2854 100644 --- a/sdk/search/azure-search-documents/swagger/src/main/java/SearchServiceCustomizations.java +++ b/sdk/search/azure-search-documents/swagger/src/main/java/SearchServiceCustomizations.java @@ -364,49 +364,62 @@ private void customizeSynonymMap(ClassCustomization classCustomization) { private void customizeSearchResourceEncryptionKey(ClassCustomization keyCustomization, ClassCustomization credentialCustomization) { keyCustomization.removeMethod("getAccessCredentials"); - - String setterReturnJavadoc = keyCustomization.getMethod("setAccessCredentials").getJavadoc().getReturn(); - keyCustomization.removeMethod("setAccessCredentials"); - - keyCustomization.addMethod(joinWithNewline( - "public String getApplicationId() {", - " return (this.accessCredentials == null) ? null : this.accessCredentials.getApplicationId();", - "}")) - .getJavadoc() - .replace(credentialCustomization.getMethod("getApplicationId").getJavadoc()); - - keyCustomization.addMethod(joinWithNewline( - "public SearchResourceEncryptionKey setApplicationId(String applicationId) {", - " if (this.accessCredentials == null) {", - " this.accessCredentials = new AzureActiveDirectoryApplicationCredentials();", - " }", - "", - " this.accessCredentials.setApplicationId(applicationId);", - " return this;", - "}")) - .getJavadoc() - .replace(credentialCustomization.getMethod("setApplicationId").getJavadoc()) - .setReturn(setterReturnJavadoc); - - keyCustomization.addMethod(joinWithNewline( - "public String getApplicationSecret() {", - " return (this.accessCredentials == null) ? null : this.accessCredentials.getApplicationSecret();", - "}")) - .getJavadoc() - .replace(credentialCustomization.getMethod("getApplicationSecret").getJavadoc()); - - keyCustomization.addMethod(joinWithNewline( - "public SearchResourceEncryptionKey setApplicationSecret(String applicationSecret) {", - " if (this.accessCredentials == null) {", - " this.accessCredentials = new AzureActiveDirectoryApplicationCredentials();", - " }", - "", - " this.accessCredentials.setApplicationSecret(applicationSecret);", - " return this;", - "}")) - .getJavadoc() - .replace(credentialCustomization.getMethod("setApplicationSecret").getJavadoc()) - .setReturn(setterReturnJavadoc); + customizeAst(keyCustomization, clazz -> { + clazz.getMethodsByName("setAccessCredentials").get(0).remove(); + + clazz.addMethod("getApplicationId", Modifier.Keyword.PUBLIC) + .setType(String.class) + .setBody(StaticJavaParser.parseBlock("{\n" + + " return (this.accessCredentials == null) ? null : this.accessCredentials.getApplicationId();\n" + + " }")) + .setJavadocComment(StaticJavaParser.parseJavadoc("* Get the applicationId property: An AAD Application ID that was granted the required access permissions to the\n" + + " * Azure Key Vault that is to be used when encrypting your data at rest. The Application ID should not be confused\n" + + " * with the Object ID for your AAD Application.\n" + + " * \n" + + " * @return the applicationId value.")); + + clazz.addMethod("setApplicationId", Modifier.Keyword.PUBLIC) + .setType(keyCustomization.getClassName()) + .addParameter(String.class, "applicationId") + .setBody(StaticJavaParser.parseBlock("{\n" + + " if (this.accessCredentials == null) {\n" + + " this.accessCredentials = new AzureActiveDirectoryApplicationCredentials();\n" + + " }\n" + + " this.accessCredentials.setApplicationId(applicationId);\n" + + " return this;\n" + + " }")) + .setJavadocComment(StaticJavaParser.parseJavadoc("* Set the applicationId property: An AAD Application ID that was granted the required access permissions to the\n" + + " * Azure Key Vault that is to be used when encrypting your data at rest. The Application ID should not be confused\n" + + " * with the Object ID for your AAD Application.\n" + + " * \n" + + " * @param applicationId the applicationId value to set.\n" + + " * @return the SearchResourceEncryptionKey object itself.")); + + clazz.addMethod("getApplicationSecret", Modifier.Keyword.PUBLIC) + .setType(String.class) + .setBody(StaticJavaParser.parseBlock("{\n" + + " return (this.accessCredentials == null) ? null : this.accessCredentials.getApplicationSecret();\n" + + " }")) + .setJavadocComment(StaticJavaParser.parseJavadoc("* Get the applicationSecret property: The authentication key of the specified AAD application.\n" + + " * \n" + + " * @return the applicationSecret value.")); + + + clazz.addMethod("setApplicationSecret", Modifier.Keyword.PUBLIC) + .setType(keyCustomization.getClassName()) + .addParameter(String.class, "applicationSecret") + .setBody(StaticJavaParser.parseBlock("{\n" + + " if (this.accessCredentials == null) {\n" + + " this.accessCredentials = new AzureActiveDirectoryApplicationCredentials();\n" + + " }\n" + + " this.accessCredentials.setApplicationSecret(applicationSecret);\n" + + " return this;\n" + + " }")) + .setJavadocComment(StaticJavaParser.parseJavadoc("* Set the applicationSecret property: The authentication key of the specified AAD application.\n" + + " * \n" + + " * @param applicationSecret the applicationSecret value to set.\n" + + " * @return the SearchResourceEncryptionKey object itself.")); + }); } private void customizeSearchSuggester(ClassCustomization classCustomization) { diff --git a/sdk/search/azure-search-perf/pom.xml b/sdk/search/azure-search-perf/pom.xml index d5e059ee78cbf..99c82327d7057 100644 --- a/sdk/search/azure-search-perf/pom.xml +++ b/sdk/search/azure-search-perf/pom.xml @@ -35,12 +35,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/security/azure-resourcemanager-security/pom.xml b/sdk/security/azure-resourcemanager-security/pom.xml index 0266ed05ffc1b..87e11f36a998e 100644 --- a/sdk/security/azure-resourcemanager-security/pom.xml +++ b/sdk/security/azure-resourcemanager-security/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/securitydevops/azure-resourcemanager-securitydevops/pom.xml b/sdk/securitydevops/azure-resourcemanager-securitydevops/pom.xml index 631df6f9d4a35..a1eaed2c65bcf 100644 --- a/sdk/securitydevops/azure-resourcemanager-securitydevops/pom.xml +++ b/sdk/securitydevops/azure-resourcemanager-securitydevops/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/securityinsights/azure-resourcemanager-securityinsights/pom.xml b/sdk/securityinsights/azure-resourcemanager-securityinsights/pom.xml index 71ead875bbe5b..5d35c522cdaf0 100644 --- a/sdk/securityinsights/azure-resourcemanager-securityinsights/pom.xml +++ b/sdk/securityinsights/azure-resourcemanager-securityinsights/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/selfhelp/azure-resourcemanager-selfhelp/pom.xml b/sdk/selfhelp/azure-resourcemanager-selfhelp/pom.xml index ece43f87f84bc..aada4fd314961 100644 --- a/sdk/selfhelp/azure-resourcemanager-selfhelp/pom.xml +++ b/sdk/selfhelp/azure-resourcemanager-selfhelp/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml b/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml index b3d5b01d22ff7..863ce3a617b81 100644 --- a/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml +++ b/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml @@ -67,12 +67,12 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 com.azure azure-core-metrics-opentelemetry - 1.0.0-beta.18 + 1.0.0-beta.19 diff --git a/sdk/servicebus/azure-messaging-servicebus-stress/src/main/java/com/azure/messaging/servicebus/stress/scenarios/MessageSenderReconnectAsync.java b/sdk/servicebus/azure-messaging-servicebus-stress/src/main/java/com/azure/messaging/servicebus/stress/scenarios/MessageSenderReconnectAsync.java new file mode 100644 index 0000000000000..d53fa251e0f70 --- /dev/null +++ b/sdk/servicebus/azure-messaging-servicebus-stress/src/main/java/com/azure/messaging/servicebus/stress/scenarios/MessageSenderReconnectAsync.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.servicebus.stress.scenarios; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.logging.ClientLogger; +import com.azure.messaging.servicebus.ServiceBusMessage; +import com.azure.messaging.servicebus.ServiceBusSenderAsyncClient; +import com.azure.messaging.servicebus.stress.util.RateLimiter; +import com.azure.messaging.servicebus.stress.util.TestUtils; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.trace.Span; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +import static com.azure.messaging.servicebus.stress.util.TestUtils.blockingWait; +import static com.azure.messaging.servicebus.stress.util.TestUtils.createMessagePayload; +import static com.azure.messaging.servicebus.stress.util.TestUtils.getSenderBuilder; + +/** + * Test ServiceBusSenderAsyncClient + */ +@Component("MessageSenderReconnectAsync") +public class MessageSenderReconnectAsync extends ServiceBusScenario { + private final static ClientLogger LOGGER = new ClientLogger(MessageSenderReconnectAsync.class); + @Value("${BATCH_SIZE:2}") + private int batchSize; + + @Value("${SEND_CONCURRENCY:5}") + private int sendConcurrency; + + private BinaryData messagePayload; + + @Override + public void run() { + messagePayload = createMessagePayload(options.getMessageSize()); + + toClose(Mono.just(1) + .repeat() + .flatMap(i -> singleRun(), sendConcurrency) + .take(options.getTestDuration()) + .parallel(sendConcurrency, 1) + .runOn(Schedulers.boundedElastic()) + .subscribe()); + + blockingWait(options.getTestDuration().plusSeconds(1)); + } + + @Override + public void recordRunOptions(Span span) { + super.recordRunOptions(span); + span.setAttribute(AttributeKey.longKey("sendConcurrency"), sendConcurrency); + span.setAttribute(AttributeKey.longKey("batchSize"), batchSize); + } + + + private Mono singleRun() { + return Mono.using( + () -> getSenderBuilder(options, false).buildAsyncClient(), + client -> singleSend(client), + ServiceBusSenderAsyncClient::close); + } + private Mono singleSend(ServiceBusSenderAsyncClient client) { + return client.createMessageBatch() + .flatMap(b -> { + for (int i = 0; i < batchSize; i ++) { + if (!b.tryAddMessage(new ServiceBusMessage(messagePayload))) { + telemetryHelper.recordError("batch is full", "createBatch"); + break; + } + } + return client.sendMessages(b); + }) + .onErrorResume(e -> { + telemetryHelper.recordError(e, "create and send batch"); + return Mono.empty(); + }) + .doOnCancel(() -> telemetryHelper.recordError("cancelled", "create and send batch")); + } +} diff --git a/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml b/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml index 27324f3442620..ddeb33bf3870c 100644 --- a/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml +++ b/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml @@ -34,12 +34,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md b/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md index fb7bdc4d6d328..62e74ebff15c0 100644 --- a/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md +++ b/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md @@ -9,6 +9,7 @@ ### 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 diff --git a/sdk/servicebus/azure-messaging-servicebus/README.md b/sdk/servicebus/azure-messaging-servicebus/README.md index 7bdf82ff1a486..4cd5ddc502488 100644 --- a/sdk/servicebus/azure-messaging-servicebus/README.md +++ b/sdk/servicebus/azure-messaging-servicebus/README.md @@ -89,7 +89,7 @@ First, add the package: com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) @@ -548,7 +548,7 @@ Guidelines](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.m [ServiceBusSenderAsyncClient]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSenderAsyncClient.java [ServiceBusSenderClient]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSenderClient.java [service_bus_create]: https://docs.microsoft.com/azure/service-bus-messaging/service-bus-create-namespace-portal -[source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/servicebus/azure-messaging-servicebus/ +[source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/servicebus/azure-messaging-servicebus/src [subscription_concept]: https://docs.microsoft.com/azure/service-bus-messaging/service-bus-queues-topics-subscriptions#topics-and-subscriptions [topic_concept]: https://docs.microsoft.com/azure/service-bus-messaging/service-bus-messaging-overview#topics [wiki_identity]: https://github.com/Azure/azure-sdk-for-java/wiki/Identity-and-Authentication diff --git a/sdk/servicebus/azure-messaging-servicebus/pom.xml b/sdk/servicebus/azure-messaging-servicebus/pom.xml index b12c2b9957da4..e0687d632fa78 100644 --- a/sdk/servicebus/azure-messaging-servicebus/pom.xml +++ b/sdk/servicebus/azure-messaging-servicebus/pom.xml @@ -57,7 +57,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -67,37 +67,37 @@ com.azure azure-core-amqp - 2.10.0-beta.1 + 2.9.4 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -148,14 +148,14 @@ com.azure azure-core-experimental - 1.0.0-beta.49 + 1.0.0-beta.50 test com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 test @@ -184,7 +184,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 8649598d6f23b..a6908ec0f5ecb 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 33c9b30217802..0000000000000 --- 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 280490f150700..fcddd200a436c 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/ServiceBusClientBuilder.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusClientBuilder.java index 245bf52460886..c5d00055f999a 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusClientBuilder.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusClientBuilder.java @@ -954,7 +954,7 @@ void onClientClose() { } // Connection-caching for the V1-Stack. - private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) { + private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer, Meter meter) { synchronized (connectionLock) { if (sharedConnection == null) { final ConnectionOptions connectionOptions = getConnectionOptions(); @@ -962,7 +962,7 @@ private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSeri final Flux connectionFlux = Mono.fromCallable(() -> { final String connectionId = StringUtil.getRandomString("MF"); final ReactorProvider provider = new ReactorProvider(); - final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); + final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider, meter); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); @@ -1037,8 +1037,8 @@ private ConnectionOptions getConnectionOptions() { } // Connection-caching for the V2-Stack. - private ReactorConnectionCache getOrCreateConnectionCache(MessageSerializer serializer) { - return v2StackSupport.getOrCreateConnectionCache(getConnectionOptions(), serializer, crossEntityTransactions); + private ReactorConnectionCache getOrCreateConnectionCache(MessageSerializer serializer, Meter meter) { + return v2StackSupport.getOrCreateConnectionCache(getConnectionOptions(), serializer, crossEntityTransactions, meter); } private static boolean isNullOrEmpty(String item) { @@ -1244,10 +1244,10 @@ boolean isSessionSyncReceiveEnabled(Configuration configuration) { // Obtain the shared connection-cache based on the V2-Stack. ReactorConnectionCache getOrCreateConnectionCache(ConnectionOptions connectionOptions, - MessageSerializer serializer, boolean crossEntityTransactions) { + MessageSerializer serializer, boolean crossEntityTransactions, Meter meter) { synchronized (connectionLock) { if (sharedConnectionCache == null) { - sharedConnectionCache = createConnectionCache(connectionOptions, serializer, crossEntityTransactions); + sharedConnectionCache = createConnectionCache(connectionOptions, serializer, crossEntityTransactions, meter); } } @@ -1345,11 +1345,11 @@ private boolean isOptedIn(Configuration configuration, ConfigurationProperty createConnectionCache(ConnectionOptions connectionOptions, - MessageSerializer serializer, boolean crossEntityTransactions) { + MessageSerializer serializer, boolean crossEntityTransactions, Meter meter) { final Supplier connectionSupplier = () -> { final String connectionId = StringUtil.getRandomString("MF"); final ReactorProvider provider = new ReactorProvider(); - final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); + final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider, meter); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getAuthorizationScope()); @@ -1425,12 +1425,13 @@ public ServiceBusSenderAsyncClient buildAsyncClient() { final ConnectionCacheWrapper connectionCacheWrapper; final Runnable onClientClose; final boolean isSenderOnV2 = v2StackSupport.isSenderAndManageRulesEnabled(configuration); + final Meter meter = createMeter(clientOptions); if (isSenderOnV2) { // Sender Client (async|sync) on the V2-Stack. - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this.v2StackSupport::onClientClose; } else { - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this::onClientClose; } final MessagingEntityType entityType = validateEntityPaths(connectionStringEntityName, topicName, @@ -1461,7 +1462,7 @@ public ServiceBusSenderAsyncClient buildAsyncClient() { } final ServiceBusSenderInstrumentation instrumentation = new ServiceBusSenderInstrumentation( - createTracer(), createMeter(), connectionCacheWrapper.getFullyQualifiedNamespace(), entityName); + createTracer(clientOptions), meter, connectionCacheWrapper.getFullyQualifiedNamespace(), entityName); return new ServiceBusSenderAsyncClient(entityName, entityType, connectionCacheWrapper, retryOptions, instrumentation, messageSerializer, onClientClose, null, clientIdentifier); @@ -1994,7 +1995,8 @@ ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() { maxAutoLockRenewDuration = Duration.ZERO; } - final ConnectionCacheWrapper connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer)); + final Meter meter = createMeter(clientOptions); + final ConnectionCacheWrapper connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer, meter)); final ReceiverOptions receiverOptions = createUnnamedSessionOptions(receiveMode, prefetchCount, maxAutoLockRenewDuration, enableAutoComplete, maxConcurrentSessions, sessionIdleTimeout); @@ -2008,7 +2010,7 @@ ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() { } final ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation( - createTracer(), createMeter(), connectionCacheWrapper.getFullyQualifiedNamespace(), + createTracer(clientOptions), meter, connectionCacheWrapper.getFullyQualifiedNamespace(), entityPath, subscriptionName, ReceiverKind.PROCESSOR); final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType, @@ -2041,13 +2043,14 @@ SessionsMessagePump buildPumpForProcessor(ClientLogger logger, } else { clientIdentifier = UUID.randomUUID().toString(); } - final ConnectionCacheWrapper connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer)); + final Meter meter = createMeter(clientOptions); + final ConnectionCacheWrapper connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer, meter)); final ServiceBusSessionAcquirer sessionAcquirer = new ServiceBusSessionAcquirer(logger, clientIdentifier, entityPath, entityType, receiveMode, retryOptions.getTryTimeout(), connectionCacheWrapper); final ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation( - createTracer(), createMeter(), connectionCacheWrapper.getFullyQualifiedNamespace(), + createTracer(clientOptions), meter, connectionCacheWrapper.getFullyQualifiedNamespace(), entityPath, subscriptionName, ReceiverKind.PROCESSOR); final Runnable onTerminate = v2StackSupport::onClientClose; @@ -2118,13 +2121,14 @@ private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoComp maxAutoLockRenewDuration = Duration.ZERO; } + final Meter meter = createMeter(clientOptions); final ConnectionCacheWrapper connectionCacheWrapper; final Runnable onClientClose; if (isV2) { - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this.v2StackSupport::onClientClose; } else { - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this::onClientClose; } final ReceiverOptions receiverOptions = createUnnamedSessionOptions(receiveMode, prefetchCount, @@ -2139,7 +2143,7 @@ private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoComp } final ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation( - createTracer(), createMeter(), connectionCacheWrapper.getFullyQualifiedNamespace(), entityPath, subscriptionName, + createTracer(clientOptions), meter, connectionCacheWrapper.getFullyQualifiedNamespace(), entityPath, subscriptionName, ReceiverKind.ASYNC_RECEIVER); return new ServiceBusSessionReceiverAsyncClient(connectionCacheWrapper.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionCacheWrapper, instrumentation, messageSerializer, @@ -2667,24 +2671,25 @@ ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed, Re final ConnectionCacheWrapper connectionCacheWrapper; final Runnable onClientClose; + final Meter meter = createMeter(clientOptions); if (receiverKind == ReceiverKind.SYNC_RECEIVER) { final boolean syncReceiveOnV2 = v2StackSupport.isNonSessionSyncReceiveEnabled(configuration); if (syncReceiveOnV2) { // "Non-Session" Sync Receiver-Client on the V2-Stack. - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this.v2StackSupport::onClientClose; } else { - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this::onClientClose; } } else { final boolean asyncReceiveOnV2 = v2StackSupport.isNonSessionAsyncReceiveEnabled(configuration); if (asyncReceiveOnV2) { // "Non-Session" Async[Reactor|Processor] Receiver-Client on the V2-Stack. - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this.v2StackSupport::onClientClose; } else { - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this::onClientClose; } } @@ -2700,7 +2705,7 @@ ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed, Re } final ServiceBusReceiverInstrumentation instrumentation = new ServiceBusReceiverInstrumentation( - createTracer(), createMeter(), connectionCacheWrapper.getFullyQualifiedNamespace(), entityPath, subscriptionName, receiverKind); + createTracer(clientOptions), meter, connectionCacheWrapper.getFullyQualifiedNamespace(), entityPath, subscriptionName, receiverKind); return new ServiceBusReceiverAsyncClient(connectionCacheWrapper.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionCacheWrapper, ServiceBusConstants.OPERATION_TIMEOUT, instrumentation, messageSerializer, onClientClose, clientIdentifier); @@ -2762,13 +2767,14 @@ public ServiceBusRuleManagerAsyncClient buildAsyncClient() { null); final ConnectionCacheWrapper connectionCacheWrapper; final Runnable onClientClose; + final Meter meter = createMeter(clientOptions); final boolean isManageRulesOnV2 = v2StackSupport.isSenderAndManageRulesEnabled(configuration); if (isManageRulesOnV2) { // RuleManager Client (async|sync) on the V2-Stack. - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionCache(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this.v2StackSupport::onClientClose; } else { - connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer)); + connectionCacheWrapper = new ConnectionCacheWrapper(getOrCreateConnectionProcessor(messageSerializer, meter)); onClientClose = ServiceBusClientBuilder.this::onClientClose; } @@ -2803,12 +2809,12 @@ private void validateAndThrow(Duration maxLockRenewalDuration, String parameterN } } - private Meter createMeter() { + private static Meter createMeter(ClientOptions clientOptions) { return MeterProvider.getDefaultProvider().createMeter(LIBRARY_NAME, LIBRARY_VERSION, clientOptions == null ? null : clientOptions.getMetricsOptions()); } - private Tracer createTracer() { + private static Tracer createTracer(ClientOptions clientOptions) { return TracerProvider.getDefaultProvider().createTracer(LIBRARY_NAME, LIBRARY_VERSION, AZ_TRACING_NAMESPACE_VALUE, clientOptions == null ? null : clientOptions.getTracingOptions()); } 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 9cb63ce4a85f2..0e7c2205227af 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 702ac378cc5d3..cccad6ed8d4d3 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 c9cc2b352fd35..fb3bb5d6e403e 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 @@ -167,7 +167,7 @@ final class SessionsMessagePump { this.instrumentation = Objects.requireNonNull(instrumentation, "'instrumentation' cannot be null"); this.sessionAcquirer = Objects.requireNonNull(sessionAcquirer, "'sessionAcquirer' cannot be null"); this.maxSessionLockRenew = Objects.requireNonNull(maxSessionLockRenew, "'maxSessionLockRenew' cannot be null."); - this.sessionIdleTimeout = sessionIdleTimeout; + this.sessionIdleTimeout = sessionIdleTimeout != null ? sessionIdleTimeout : retryPolicy.getRetryOptions().getTryTimeout(); this.maxConcurrentSessions = maxConcurrentSessions; this.concurrencyPerSession = concurrencyPerSession; this.prefetch = prefetch; @@ -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 0000000000000..830f520863899 --- /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/ManagementChannel.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ManagementChannel.java index ac96a2fc67b95..8e88884d9ad00 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ManagementChannel.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ManagementChannel.java @@ -147,9 +147,9 @@ public Mono getSessionState(String sessionId, String associatedLinkName) final Object value = ((AmqpValue) response.getBody()).getValue(); if (!(value instanceof Map)) { - return monoError(logger, Exceptions.propagate(new AmqpException(false, String.format( + return monoError(logger, new AmqpException(false, String.format( "Body not expected when renewing session. Id: %s. Value: %s", sessionId, value), - getErrorContext()))); + getErrorContext())); } @SuppressWarnings("unchecked") final Map map = (Map) value; @@ -352,8 +352,8 @@ public Flux schedule(List messages, OffsetDateTime sche "Error sending. Size of the payload exceeded maximum message size: %s kb", maxLinkSize / 1024); final AmqpErrorContext errorContext = channel.getErrorContext(); - return monoError(logger, Exceptions.propagate(new AmqpException(false, - AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, errorContext))); + return monoError(logger, new AmqpException(false, + AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, errorContext)); } final Map messageEntry = new HashMap<>(); @@ -524,9 +524,9 @@ public Flux listRules() { } else if (statusCode == AmqpResponseCode.NO_CONTENT) { list = Collections.emptyList(); } else { - throw logger.logExceptionAsError(Exceptions.propagate(new AmqpException(true, + throw logger.logExceptionAsWarning(new AmqpException(true, "Get rules response error. Could not get rules.", - getErrorContext()))); + getErrorContext())); } return Flux.fromIterable(list); @@ -597,7 +597,7 @@ private Mono sendWithVerify(RequestResponseChannel channel, Message mes private Mono errorIfEmpty(RequestResponseChannel channel) { return Mono.error(() -> { String error = String.format("entityPath[%s] No response received from management channel.", entityPath); - return logger.logExceptionAsError(new AmqpException(true, error, channel.getErrorContext())); + return logger.logExceptionAsWarning(new AmqpException(true, error, channel.getErrorContext())); }); } diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ServiceBusConnectionProcessor.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ServiceBusConnectionProcessor.java index 80d91ad2774d2..cbe8393c123aa 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ServiceBusConnectionProcessor.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ServiceBusConnectionProcessor.java @@ -6,8 +6,8 @@ import com.azure.core.amqp.AmqpRetryOptions; import com.azure.core.amqp.implementation.AmqpChannelProcessor; import com.azure.core.amqp.implementation.RetryUtil; -import com.azure.core.util.logging.ClientLogger; +import java.util.Collections; import java.util.Objects; /** @@ -20,8 +20,8 @@ public class ServiceBusConnectionProcessor extends AmqpChannelProcessor channel.getEndpointStates(), - RetryUtil.getRetryPolicy(retryOptions), new ClientLogger(ServiceBusConnectionProcessor.class)); + super(fullyQualifiedNamespace, channel -> channel.getEndpointStates(), + RetryUtil.getRetryPolicy(retryOptions), Collections.emptyMap()); this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ServiceBusReactorAmqpConnection.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ServiceBusReactorAmqpConnection.java index 42e63a7a18b32..8c800c80203c3 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ServiceBusReactorAmqpConnection.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ServiceBusReactorAmqpConnection.java @@ -31,6 +31,7 @@ import static com.azure.core.amqp.implementation.ClientConstants.ENTITY_PATH_KEY; import static com.azure.core.amqp.implementation.ClientConstants.LINK_NAME_KEY; +import static com.azure.core.util.FluxUtil.monoError; /** * A proton-j AMQP connection to an Azure Service Bus instance. @@ -95,9 +96,9 @@ public ServiceBusReactorAmqpConnection(String connectionId, ConnectionOptions co @Override public Mono getManagementNode(String entityPath, MessagingEntityType entityType) { if (isDisposed()) { - return Mono.error(LOGGER.logExceptionAsError(new IllegalStateException(String.format( + return monoError(LOGGER.atWarning(), new IllegalStateException(String.format( "connectionId[%s]: Connection is disposed. Cannot get management instance for '%s'", - connectionId, entityPath)))); + connectionId, entityPath))); } final String entityTypePath = String.join("-", entityType.toString(), entityPath); 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 5cb4616c97bdc..cb54adcb41a2f 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 4f24630ec75f7..532a71a249f0a 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/IntegrationTestBase.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/IntegrationTestBase.java index 8f0457dd89b32..4921dda64f3ad 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/IntegrationTestBase.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/IntegrationTestBase.java @@ -11,6 +11,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.experimental.util.tracing.LoggingTracerProvider; import com.azure.core.test.TestBase; +import com.azure.core.test.TestContextManager; import com.azure.core.test.TestMode; import com.azure.core.test.utils.TestConfigurationSource; import com.azure.core.util.AsyncCloseable; @@ -29,7 +30,6 @@ import com.azure.messaging.servicebus.models.ServiceBusReceiveMode; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.params.provider.Arguments; import reactor.core.Disposable; import reactor.core.publisher.Mono; @@ -37,7 +37,6 @@ import reactor.core.scheduler.Schedulers; import java.io.Closeable; -import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.Proxy; import java.nio.charset.StandardCharsets; @@ -84,11 +83,10 @@ protected IntegrationTestBase(ClientLogger logger) { } @BeforeEach - public void setupTest(TestInfo testInfo) { - Method testMethod = testInfo.getTestMethod().orElseGet(null); - testName = String.format("%s-%s", - testMethod == null ? "unknown" : testMethod.getName(), - testInfo.getDisplayName()); + @Override + public void setupTest(TestContextManager testContextManager) { + this.testContextManager = testContextManager; + testName = testContextManager.getTrackerTestName(); logger.info("========= SET-UP [{}] =========", testName); @@ -100,9 +98,9 @@ public void setupTest(TestInfo testInfo) { } // These are overridden because we don't use the Interceptor Manager. - @Override @AfterEach - public void teardownTest(TestInfo testInfo) { + @Override + public void teardownTest() { logger.info("========= TEARDOWN [{}] =========", testName); afterTest(); @@ -473,10 +471,16 @@ protected final Configuration v1OrV2(boolean isV2) { if (isV2) { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "true"); + configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "true"); + configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "true"); + configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "true"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "true"); } else { configSource.put("com.azure.messaging.servicebus.nonSession.asyncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.nonSession.syncReceive.v2", "false"); + configSource.put("com.azure.messaging.servicebus.session.processor.asyncReceive.v2", "false"); + configSource.put("com.azure.messaging.servicebus.session.reactor.asyncReceive.v2", "false"); + configSource.put("com.azure.messaging.servicebus.session.syncReceive.v2", "false"); configSource.put("com.azure.messaging.servicebus.sendAndManageRules.v2", "false"); } return new ConfigurationBuilder(configSource) 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 7047f8138369a..1dff7bec61849 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 033b74509fed8..98b6c3f717874 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 0b46e7fb54732..9709bc8f77261 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 42052a460dc0d..4686edf67643a 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 2da9dc8d8788b..d62e825e3a4d4 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 05804738519fe..aa93866c66fd8 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 6416b0409ef58..8531bdedeb7a6 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 7a50929d25f95..6bc5730921d20 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 3f108c6b66781..66720fb5fd244 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 46597b57f9631..55766945d4e4f 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/servicefabric/azure-resourcemanager-servicefabric/pom.xml b/sdk/servicefabric/azure-resourcemanager-servicefabric/pom.xml index fd08ce4d8641c..11162a92f26a7 100644 --- a/sdk/servicefabric/azure-resourcemanager-servicefabric/pom.xml +++ b/sdk/servicefabric/azure-resourcemanager-servicefabric/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/servicelinker/azure-resourcemanager-servicelinker/pom.xml b/sdk/servicelinker/azure-resourcemanager-servicelinker/pom.xml index afbc68cee54c6..d59c8b6298e52 100644 --- a/sdk/servicelinker/azure-resourcemanager-servicelinker/pom.xml +++ b/sdk/servicelinker/azure-resourcemanager-servicelinker/pom.xml @@ -44,17 +44,17 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/pom.xml b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/pom.xml index e6553ef1b8c2c..7546f84a81122 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/pom.xml +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/signalr/azure-resourcemanager-signalr/pom.xml b/sdk/signalr/azure-resourcemanager-signalr/pom.xml index 3b63128c1b389..3b4aadd396636 100644 --- a/sdk/signalr/azure-resourcemanager-signalr/pom.xml +++ b/sdk/signalr/azure-resourcemanager-signalr/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/sphere/azure-resourcemanager-sphere/pom.xml b/sdk/sphere/azure-resourcemanager-sphere/pom.xml index 3461d6eaa21f4..fb5ad78b6a8c6 100644 --- a/sdk/sphere/azure-resourcemanager-sphere/pom.xml +++ b/sdk/sphere/azure-resourcemanager-sphere/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md b/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md index b2e844f18e233..14054c03cf606 100644 --- a/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md +++ b/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md @@ -9,6 +9,7 @@ #### 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 diff --git a/sdk/spring/azure-spring-data-cosmos/pom.xml b/sdk/spring/azure-spring-data-cosmos/pom.xml index bef852eef7a8a..ff5b5d10fe5a8 100644 --- a/sdk/spring/azure-spring-data-cosmos/pom.xml +++ b/sdk/spring/azure-spring-data-cosmos/pom.xml @@ -98,7 +98,7 @@ com.azure azure-cosmos - 4.58.0 + 4.59.0 com.fasterxml.jackson.module 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 b33a473d6b2d4..20612e32dc35c 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 9a5248b2dc248..90f30b632128b 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 dd13d14ccf5a8..56a1a65418a80 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 823b7897bc8fa..03bf88ce9359e 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/pom.xml b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml index ca0221a0e4fc6..1fba53d1705f8 100644 --- a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml +++ b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml @@ -63,13 +63,13 @@ com.azure azure-core - 1.48.0 + 1.49.0 true com.azure azure-cosmos - 4.58.0 + 4.59.0 true diff --git a/sdk/spring/spring-cloud-azure-actuator/pom.xml b/sdk/spring/spring-cloud-azure-actuator/pom.xml index 98c81e9152876..de867f093e466 100644 --- a/sdk/spring/spring-cloud-azure-actuator/pom.xml +++ b/sdk/spring/spring-cloud-azure-actuator/pom.xml @@ -51,13 +51,13 @@ com.azure azure-core - 1.48.0 + 1.49.0 true com.azure azure-cosmos - 4.58.0 + 4.59.0 true diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml b/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml index ac7344ffe6059..9aca0209389dd 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml @@ -43,7 +43,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -53,7 +53,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 com.azure 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 1a09cdf8ed1aa..e9fe610f0e4c4 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/pom.xml b/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml index a6051cc776db2..6cd733b405b20 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml +++ b/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml @@ -151,19 +151,19 @@ com.azure azure-core - 1.48.0 + 1.49.0 true com.azure azure-identity - 1.12.0 + 1.12.1 true com.azure azure-cosmos - 4.58.0 + 4.59.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 5dca4d976bd8e..99546b4791518 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 d49e866570118..98024e7579db8 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 bd8b448ca437e..8ea467b01370a 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 e198123d55a96..fff6275c6c854 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/pom.xml b/sdk/spring/spring-cloud-azure-core/pom.xml index 15eaead908761..e52f7d5e25efd 100644 --- a/sdk/spring/spring-cloud-azure-core/pom.xml +++ b/sdk/spring/spring-cloud-azure-core/pom.xml @@ -41,22 +41,22 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-identity - 1.12.0 + 1.12.1 com.azure azure-core-amqp - 2.9.3 + 2.9.4 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/spring/spring-cloud-azure-integration-tests/pom.xml b/sdk/spring/spring-cloud-azure-integration-tests/pom.xml index ceda5d77f5b0e..a27b86269a210 100644 --- a/sdk/spring/spring-cloud-azure-integration-tests/pom.xml +++ b/sdk/spring/spring-cloud-azure-integration-tests/pom.xml @@ -131,7 +131,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 diff --git a/sdk/spring/spring-cloud-azure-service/pom.xml b/sdk/spring/spring-cloud-azure-service/pom.xml index 5eb12ba528cfa..9cc495eb56df0 100644 --- a/sdk/spring/spring-cloud-azure-service/pom.xml +++ b/sdk/spring/spring-cloud-azure-service/pom.xml @@ -44,7 +44,7 @@ com.azure azure-cosmos - 4.58.0 + 4.59.0 true diff --git a/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml b/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml index d29856ddb19d4..9614134669354 100644 --- a/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml @@ -93,7 +93,7 @@ com.azure azure-cosmos - 4.58.0 + 4.59.0 diff --git a/sdk/spring/spring-cloud-azure-starter-monitor-test/pom.xml b/sdk/spring/spring-cloud-azure-starter-monitor-test/pom.xml index fdc0b6f6c483d..4117f0adbe44c 100644 --- a/sdk/spring/spring-cloud-azure-starter-monitor-test/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-monitor-test/pom.xml @@ -60,7 +60,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test 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 42ea6e7e02c28..42e4ce22afa95 100644 --- a/sdk/spring/spring-cloud-azure-starter-servicebus-jms/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-servicebus-jms/pom.xml @@ -122,13 +122,13 @@ currently released version and a lower version is resolved. --> com.azure azure-core - 1.48.0 + 1.49.0 true com.azure azure-identity - 1.12.0 + 1.12.1 true diff --git a/sdk/spring/spring-cloud-azure-trace-sleuth/pom.xml b/sdk/spring/spring-cloud-azure-trace-sleuth/pom.xml index ac4c691702efc..08f755475e381 100644 --- a/sdk/spring/spring-cloud-azure-trace-sleuth/pom.xml +++ b/sdk/spring/spring-cloud-azure-trace-sleuth/pom.xml @@ -66,7 +66,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/spring/spring-integration-azure-servicebus/pom.xml b/sdk/spring/spring-integration-azure-servicebus/pom.xml index 089d3c18f02e7..55c5376e74522 100644 --- a/sdk/spring/spring-integration-azure-servicebus/pom.xml +++ b/sdk/spring/spring-integration-azure-servicebus/pom.xml @@ -70,7 +70,7 @@ com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 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 7e931c350b6e8..0a6109aa71dbb 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/pom.xml b/sdk/spring/spring-messaging-azure-servicebus/pom.xml index 5462aa00ba45b..5a8526bbca21b 100644 --- a/sdk/spring/spring-messaging-azure-servicebus/pom.xml +++ b/sdk/spring/spring-messaging-azure-servicebus/pom.xml @@ -55,7 +55,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 org.springframework @@ -122,7 +122,7 @@ com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 test diff --git a/sdk/spring/spring-messaging-azure-storage-queue/pom.xml b/sdk/spring/spring-messaging-azure-storage-queue/pom.xml index 620bfb1ddc5f9..8df3a2d0ca0f0 100644 --- a/sdk/spring/spring-messaging-azure-storage-queue/pom.xml +++ b/sdk/spring/spring-messaging-azure-storage-queue/pom.xml @@ -54,7 +54,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 @@ -98,7 +98,7 @@ com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 test diff --git a/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/pom.xml b/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/pom.xml index 4d579b89c23e9..01bef12ff971c 100644 --- a/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/pom.xml +++ b/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/pom.xml b/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/pom.xml index 026be93274473..cfbde5ba6a7d8 100644 --- a/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/pom.xml +++ b/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/standbypool/azure-resourcemanager-standbypool/pom.xml b/sdk/standbypool/azure-resourcemanager-standbypool/pom.xml index 8e9a6854e6602..0786c388ac656 100644 --- a/sdk/standbypool/azure-resourcemanager-standbypool/pom.xml +++ b/sdk/standbypool/azure-resourcemanager-standbypool/pom.xml @@ -51,23 +51,23 @@ Code generated by Microsoft (R) AutoRest Code Generator. com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/storage/azure-storage-blob-batch/pom.xml b/sdk/storage/azure-storage-blob-batch/pom.xml index 71c05bbb1b4e5..e2bec14ebe691 100644 --- a/sdk/storage/azure-storage-blob-batch/pom.xml +++ b/sdk/storage/azure-storage-blob-batch/pom.xml @@ -55,12 +55,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -95,13 +95,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -125,13 +125,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -165,7 +165,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/storage/azure-storage-blob-changefeed/pom.xml b/sdk/storage/azure-storage-blob-changefeed/pom.xml index af19a072d3c9c..83432f89e6699 100644 --- a/sdk/storage/azure-storage-blob-changefeed/pom.xml +++ b/sdk/storage/azure-storage-blob-changefeed/pom.xml @@ -62,12 +62,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -102,13 +102,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -140,13 +140,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -198,7 +198,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/storage/azure-storage-blob-cryptography/pom.xml b/sdk/storage/azure-storage-blob-cryptography/pom.xml index 2cef15b1f1077..e621d002af51b 100644 --- a/sdk/storage/azure-storage-blob-cryptography/pom.xml +++ b/sdk/storage/azure-storage-blob-cryptography/pom.xml @@ -56,12 +56,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -86,7 +86,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -126,13 +126,13 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-security-keyvault-keys - 4.8.2 + 4.8.3 test @@ -156,13 +156,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -196,7 +196,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/storage/azure-storage-blob-nio/pom.xml b/sdk/storage/azure-storage-blob-nio/pom.xml index 83a43ec18834e..04303e035c9c9 100644 --- a/sdk/storage/azure-storage-blob-nio/pom.xml +++ b/sdk/storage/azure-storage-blob-nio/pom.xml @@ -53,12 +53,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -83,7 +83,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -119,13 +119,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -179,7 +179,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/storage/azure-storage-blob-stress/pom.xml b/sdk/storage/azure-storage-blob-stress/pom.xml index fe67d52f55899..4f0aed7eacfdc 100644 --- a/sdk/storage/azure-storage-blob-stress/pom.xml +++ b/sdk/storage/azure-storage-blob-stress/pom.xml @@ -30,12 +30,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -68,7 +68,7 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 diff --git a/sdk/storage/azure-storage-blob/assets.json b/sdk/storage/azure-storage-blob/assets.json index 54488582adbbf..e034c9593e7eb 100644 --- a/sdk/storage/azure-storage-blob/assets.json +++ b/sdk/storage/azure-storage-blob/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/storage/azure-storage-blob", - "Tag": "java/storage/azure-storage-blob_7e4a0926e9" + "Tag": "java/storage/azure-storage-blob_bd8a4072b4" } diff --git a/sdk/storage/azure-storage-blob/pom.xml b/sdk/storage/azure-storage-blob/pom.xml index 6682095d7d5a6..9b5114104bea5 100644 --- a/sdk/storage/azure-storage-blob/pom.xml +++ b/sdk/storage/azure-storage-blob/pom.xml @@ -70,12 +70,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -114,13 +114,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -182,13 +182,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -291,7 +291,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 0a3e792ec5fbb..7fed3d1953bb5 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 e0542697dd501..275488bc0ec62 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-common/pom.xml b/sdk/storage/azure-storage-common/pom.xml index c56a400a1177a..e7b785ddeccbe 100644 --- a/sdk/storage/azure-storage-common/pom.xml +++ b/sdk/storage/azure-storage-common/pom.xml @@ -58,12 +58,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -85,13 +85,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -115,13 +115,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -206,7 +206,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/storage/azure-storage-file-datalake-stress/pom.xml b/sdk/storage/azure-storage-file-datalake-stress/pom.xml index 1210e977cba07..19f6397638227 100644 --- a/sdk/storage/azure-storage-file-datalake-stress/pom.xml +++ b/sdk/storage/azure-storage-file-datalake-stress/pom.xml @@ -30,12 +30,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -68,7 +68,7 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 diff --git a/sdk/storage/azure-storage-file-datalake/pom.xml b/sdk/storage/azure-storage-file-datalake/pom.xml index 77c2d98e92a77..b387394d78254 100644 --- a/sdk/storage/azure-storage-file-datalake/pom.xml +++ b/sdk/storage/azure-storage-file-datalake/pom.xml @@ -66,12 +66,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -106,13 +106,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -142,13 +142,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -222,7 +222,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/storage/azure-storage-file-share-stress/pom.xml b/sdk/storage/azure-storage-file-share-stress/pom.xml index 87f919894d28d..d1e5560be6ad0 100644 --- a/sdk/storage/azure-storage-file-share-stress/pom.xml +++ b/sdk/storage/azure-storage-file-share-stress/pom.xml @@ -30,12 +30,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -68,7 +68,7 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 diff --git a/sdk/storage/azure-storage-file-share/pom.xml b/sdk/storage/azure-storage-file-share/pom.xml index d1337935c0c37..4515240b37fc6 100644 --- a/sdk/storage/azure-storage-file-share/pom.xml +++ b/sdk/storage/azure-storage-file-share/pom.xml @@ -71,12 +71,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -106,7 +106,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -136,7 +136,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -148,13 +148,13 @@ com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -209,7 +209,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test 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 4a9a58e0cd8b0..3c795ad37af99 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/storage/azure-storage-internal-avro/pom.xml b/sdk/storage/azure-storage-internal-avro/pom.xml index c1eb812dae6e6..4b118063b76cb 100644 --- a/sdk/storage/azure-storage-internal-avro/pom.xml +++ b/sdk/storage/azure-storage-internal-avro/pom.xml @@ -53,7 +53,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure @@ -88,7 +88,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test diff --git a/sdk/storage/azure-storage-perf/pom.xml b/sdk/storage/azure-storage-perf/pom.xml index 5cddc5322ae30..41d959a0e33cd 100644 --- a/sdk/storage/azure-storage-perf/pom.xml +++ b/sdk/storage/azure-storage-perf/pom.xml @@ -55,18 +55,18 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-security-keyvault-keys - 4.8.2 + 4.8.3 @@ -130,7 +130,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 diff --git a/sdk/storage/azure-storage-queue/pom.xml b/sdk/storage/azure-storage-queue/pom.xml index 775744e82bf4c..6327d32743e20 100644 --- a/sdk/storage/azure-storage-queue/pom.xml +++ b/sdk/storage/azure-storage-queue/pom.xml @@ -66,12 +66,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -90,7 +90,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -120,19 +120,19 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -187,7 +187,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/storage/azure-storage-stress/pom.xml b/sdk/storage/azure-storage-stress/pom.xml index 64e1c784b8c70..8350241c9e3b7 100644 --- a/sdk/storage/azure-storage-stress/pom.xml +++ b/sdk/storage/azure-storage-stress/pom.xml @@ -30,12 +30,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -63,7 +63,7 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.45 + 1.0.0-beta.46 diff --git a/sdk/storage/microsoft-azure-storage-blob/pom.xml b/sdk/storage/microsoft-azure-storage-blob/pom.xml index 4ba43ad9d3052..c0e3c63e1dce9 100644 --- a/sdk/storage/microsoft-azure-storage-blob/pom.xml +++ b/sdk/storage/microsoft-azure-storage-blob/pom.xml @@ -76,7 +76,7 @@ org.spockframework spock-core - 2.4-M1-groovy-4.0 + 2.4-M4-groovy-4.0 test diff --git a/sdk/storageactions/azure-resourcemanager-storageactions/pom.xml b/sdk/storageactions/azure-resourcemanager-storageactions/pom.xml index be28a80b68b83..478113ffb6675 100644 --- a/sdk/storageactions/azure-resourcemanager-storageactions/pom.xml +++ b/sdk/storageactions/azure-resourcemanager-storageactions/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/storagecache/azure-resourcemanager-storagecache/pom.xml b/sdk/storagecache/azure-resourcemanager-storagecache/pom.xml index 601fb8f3607f7..8f1e1d0e4fcbe 100644 --- a/sdk/storagecache/azure-resourcemanager-storagecache/pom.xml +++ b/sdk/storagecache/azure-resourcemanager-storagecache/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/storageimportexport/azure-resourcemanager-storageimportexport/pom.xml b/sdk/storageimportexport/azure-resourcemanager-storageimportexport/pom.xml index 3d2dc49ea5cbf..9e47cb3e6e488 100644 --- a/sdk/storageimportexport/azure-resourcemanager-storageimportexport/pom.xml +++ b/sdk/storageimportexport/azure-resourcemanager-storageimportexport/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/storagemover/azure-resourcemanager-storagemover/pom.xml b/sdk/storagemover/azure-resourcemanager-storagemover/pom.xml index 13b9c88c5cccf..063ce81afa647 100644 --- a/sdk/storagemover/azure-resourcemanager-storagemover/pom.xml +++ b/sdk/storagemover/azure-resourcemanager-storagemover/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/storagepool/azure-resourcemanager-storagepool/pom.xml b/sdk/storagepool/azure-resourcemanager-storagepool/pom.xml index f9a657b69aa94..8cd3ec1e5b69c 100644 --- a/sdk/storagepool/azure-resourcemanager-storagepool/pom.xml +++ b/sdk/storagepool/azure-resourcemanager-storagepool/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/streamanalytics/azure-resourcemanager-streamanalytics/pom.xml b/sdk/streamanalytics/azure-resourcemanager-streamanalytics/pom.xml index 46f5bad868224..7dc44128c3f3f 100644 --- a/sdk/streamanalytics/azure-resourcemanager-streamanalytics/pom.xml +++ b/sdk/streamanalytics/azure-resourcemanager-streamanalytics/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/subscription/azure-resourcemanager-subscription/pom.xml b/sdk/subscription/azure-resourcemanager-subscription/pom.xml index 9034425ab02ed..2898c44010ec4 100644 --- a/sdk/subscription/azure-resourcemanager-subscription/pom.xml +++ b/sdk/subscription/azure-resourcemanager-subscription/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/support/azure-resourcemanager-support/pom.xml b/sdk/support/azure-resourcemanager-support/pom.xml index b418368e5725b..1352bbdc463ac 100644 --- a/sdk/support/azure-resourcemanager-support/pom.xml +++ b/sdk/support/azure-resourcemanager-support/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/synapse/azure-analytics-synapse-accesscontrol/pom.xml b/sdk/synapse/azure-analytics-synapse-accesscontrol/pom.xml index d4575847fed92..0a533d44215a8 100644 --- a/sdk/synapse/azure-analytics-synapse-accesscontrol/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-accesscontrol/pom.xml @@ -41,31 +41,31 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -89,7 +89,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -103,7 +103,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/pom.xml b/sdk/synapse/azure-analytics-synapse-artifacts/pom.xml index 2179b1a2f8462..6970544a274f1 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-artifacts/pom.xml @@ -41,31 +41,31 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -89,7 +89,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -103,7 +103,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/pom.xml b/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/pom.xml index 1d002b3feda01..b226fa2cfcec1 100644 --- a/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/pom.xml @@ -41,31 +41,31 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -89,7 +89,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -103,7 +103,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/synapse/azure-analytics-synapse-monitoring/pom.xml b/sdk/synapse/azure-analytics-synapse-monitoring/pom.xml index 1e83efecfe799..7eb95c650d20e 100644 --- a/sdk/synapse/azure-analytics-synapse-monitoring/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-monitoring/pom.xml @@ -41,31 +41,31 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -89,7 +89,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -103,7 +103,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/synapse/azure-analytics-synapse-spark/pom.xml b/sdk/synapse/azure-analytics-synapse-spark/pom.xml index 3c839d29bdd5e..af50d888b3036 100644 --- a/sdk/synapse/azure-analytics-synapse-spark/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-spark/pom.xml @@ -47,31 +47,31 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -95,7 +95,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -109,7 +109,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/synapse/azure-resourcemanager-synapse/pom.xml b/sdk/synapse/azure-resourcemanager-synapse/pom.xml index 60deb441e6d66..e9b540d24be36 100644 --- a/sdk/synapse/azure-resourcemanager-synapse/pom.xml +++ b/sdk/synapse/azure-resourcemanager-synapse/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/tables/azure-data-tables-perf/pom.xml b/sdk/tables/azure-data-tables-perf/pom.xml index 96910f81b08e7..9c7f29b11ec89 100644 --- a/sdk/tables/azure-data-tables-perf/pom.xml +++ b/sdk/tables/azure-data-tables-perf/pom.xml @@ -30,7 +30,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 com.azure @@ -41,12 +41,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/tables/azure-data-tables/pom.xml b/sdk/tables/azure-data-tables/pom.xml index 74167d7d36e5b..0a173e4e707bc 100644 --- a/sdk/tables/azure-data-tables/pom.xml +++ b/sdk/tables/azure-data-tables/pom.xml @@ -48,12 +48,12 @@ Licensed under the MIT License. com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -92,13 +92,13 @@ Licensed under the MIT License. com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/template/azure-sdk-template-three/pom.xml b/sdk/template/azure-sdk-template-three/pom.xml index 461d988504cd9..e8b3d64ae0807 100644 --- a/sdk/template/azure-sdk-template-three/pom.xml +++ b/sdk/template/azure-sdk-template-three/pom.xml @@ -41,7 +41,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure diff --git a/sdk/template/azure-sdk-template-two/pom.xml b/sdk/template/azure-sdk-template-two/pom.xml index 7144fd45980a3..035c5f0e714a0 100644 --- a/sdk/template/azure-sdk-template-two/pom.xml +++ b/sdk/template/azure-sdk-template-two/pom.xml @@ -41,7 +41,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure diff --git a/sdk/template/azure-sdk-template/pom.xml b/sdk/template/azure-sdk-template/pom.xml index f59c5765430fc..b5de7593b0999 100644 --- a/sdk/template/azure-sdk-template/pom.xml +++ b/sdk/template/azure-sdk-template/pom.xml @@ -41,7 +41,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 org.junit.jupiter diff --git a/sdk/template/azure-template-perf/pom.xml b/sdk/template/azure-template-perf/pom.xml index 6a3b4746d5a39..4960fba08ce28 100644 --- a/sdk/template/azure-template-perf/pom.xml +++ b/sdk/template/azure-template-perf/pom.xml @@ -37,7 +37,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 diff --git a/sdk/template/azure-template-stress/pom.xml b/sdk/template/azure-template-stress/pom.xml index cea5548cf1899..21894bfdd6b26 100644 --- a/sdk/template/azure-template-stress/pom.xml +++ b/sdk/template/azure-template-stress/pom.xml @@ -33,28 +33,28 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 io.vertx diff --git a/sdk/textanalytics/azure-ai-textanalytics-perf/pom.xml b/sdk/textanalytics/azure-ai-textanalytics-perf/pom.xml index 0e3bcfb59ffed..2c67be09fe48e 100644 --- a/sdk/textanalytics/azure-ai-textanalytics-perf/pom.xml +++ b/sdk/textanalytics/azure-ai-textanalytics-perf/pom.xml @@ -38,12 +38,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -107,7 +107,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 diff --git a/sdk/textanalytics/azure-ai-textanalytics/README.md b/sdk/textanalytics/azure-ai-textanalytics/README.md index abade4defd470..748e39b75bbc8 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/README.md +++ b/sdk/textanalytics/azure-ai-textanalytics/README.md @@ -141,7 +141,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.11.4 + 1.12.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/textanalytics/azure-ai-textanalytics/pom.xml b/sdk/textanalytics/azure-ai-textanalytics/pom.xml index f45b9e98c5d4e..c3bda200c3d01 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/pom.xml +++ b/sdk/textanalytics/azure-ai-textanalytics/pom.xml @@ -46,12 +46,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.azure @@ -73,19 +73,19 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-core-http-okhttp - 1.11.20 + 1.11.21 test com.azure azure-core-http-vertx - 1.0.0-beta.17 + 1.0.0-beta.18 test @@ -109,7 +109,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -124,7 +124,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.12 + 1.0.0-beta.13 test diff --git a/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/pom.xml b/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/pom.xml index b4cf1ef9d6e77..15fc532d1983a 100644 --- a/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/pom.xml +++ b/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/tools/azure-sdk-build-tool/pom.xml b/sdk/tools/azure-sdk-build-tool/pom.xml index a8752c033b593..b78e9db6457cc 100644 --- a/sdk/tools/azure-sdk-build-tool/pom.xml +++ b/sdk/tools/azure-sdk-build-tool/pom.xml @@ -101,12 +101,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 diff --git a/sdk/translation/azure-ai-documenttranslator/pom.xml b/sdk/translation/azure-ai-documenttranslator/pom.xml index 9158d31c671e8..c61ac45445751 100644 --- a/sdk/translation/azure-ai-documenttranslator/pom.xml +++ b/sdk/translation/azure-ai-documenttranslator/pom.xml @@ -41,17 +41,17 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-experimental - 1.0.0-beta.49 + 1.0.0-beta.50 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -76,13 +76,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -100,7 +100,7 @@ com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 test diff --git a/sdk/translation/azure-ai-translation-text/pom.xml b/sdk/translation/azure-ai-translation-text/pom.xml index 28794993525e3..e4c9ee13278ae 100644 --- a/sdk/translation/azure-ai-translation-text/pom.xml +++ b/sdk/translation/azure-ai-translation-text/pom.xml @@ -47,17 +47,17 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-experimental - 1.0.0-beta.49 + 1.0.0-beta.50 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 @@ -82,13 +82,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test @@ -106,7 +106,7 @@ com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 test diff --git a/sdk/videoanalyzer/azure-media-videoanalyzer-edge/pom.xml b/sdk/videoanalyzer/azure-media-videoanalyzer-edge/pom.xml index 412d6e8543eca..da247f2e918aa 100644 --- a/sdk/videoanalyzer/azure-media-videoanalyzer-edge/pom.xml +++ b/sdk/videoanalyzer/azure-media-videoanalyzer-edge/pom.xml @@ -35,7 +35,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 org.junit.jupiter @@ -58,7 +58,7 @@ com.azure azure-core-serializer-json-jackson - 1.4.11 + 1.4.12 test diff --git a/sdk/videoanalyzer/azure-resourcemanager-videoanalyzer/pom.xml b/sdk/videoanalyzer/azure-resourcemanager-videoanalyzer/pom.xml index b6075df4b8dee..1428a3272950b 100644 --- a/sdk/videoanalyzer/azure-resourcemanager-videoanalyzer/pom.xml +++ b/sdk/videoanalyzer/azure-resourcemanager-videoanalyzer/pom.xml @@ -44,12 +44,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 diff --git a/sdk/vision/azure-ai-vision-imageanalysis/pom.xml b/sdk/vision/azure-ai-vision-imageanalysis/pom.xml index b6203a721aa12..b96e26bc7fbf8 100644 --- a/sdk/vision/azure-ai-vision-imageanalysis/pom.xml +++ b/sdk/vision/azure-ai-vision-imageanalysis/pom.xml @@ -48,12 +48,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 org.junit.jupiter @@ -90,13 +90,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test 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 12484368612ec..c9179536e7f5b 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/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/pom.xml b/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/pom.xml index 22467b57d3795..6ced62fd35108 100644 --- a/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/pom.xml +++ b/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/pom.xml @@ -44,23 +44,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/voiceservices/azure-resourcemanager-voiceservices/pom.xml b/sdk/voiceservices/azure-resourcemanager-voiceservices/pom.xml index 62c8f8e00136a..ac1524ce18e79 100644 --- a/sdk/voiceservices/azure-resourcemanager-voiceservices/pom.xml +++ b/sdk/voiceservices/azure-resourcemanager-voiceservices/pom.xml @@ -50,23 +50,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/pom.xml b/sdk/webpubsub/azure-messaging-webpubsub-client/pom.xml index 8515c6dc87afe..6e99065451f85 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/pom.xml +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/pom.xml @@ -42,7 +42,7 @@ com.azure azure-core - 1.48.0 + 1.49.0 @@ -56,7 +56,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -80,7 +80,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test 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 dd6fc1ad5aff8..316e35d9a0db7 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(); } diff --git a/sdk/webpubsub/azure-messaging-webpubsub/pom.xml b/sdk/webpubsub/azure-messaging-webpubsub/pom.xml index 6f33192de7b08..43285d85cbb57 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub/pom.xml +++ b/sdk/webpubsub/azure-messaging-webpubsub/pom.xml @@ -36,12 +36,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-http-netty - 1.14.2 + 1.15.0 com.nimbusds @@ -53,7 +53,7 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test @@ -89,7 +89,7 @@ com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/webpubsub/azure-resourcemanager-webpubsub/pom.xml b/sdk/webpubsub/azure-resourcemanager-webpubsub/pom.xml index eab21d35b4a9d..2105826564a5d 100644 --- a/sdk/webpubsub/azure-resourcemanager-webpubsub/pom.xml +++ b/sdk/webpubsub/azure-resourcemanager-webpubsub/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/workloads/azure-resourcemanager-workloads/pom.xml b/sdk/workloads/azure-resourcemanager-workloads/pom.xml index d841252d6607e..b94fb98e04c71 100644 --- a/sdk/workloads/azure-resourcemanager-workloads/pom.xml +++ b/sdk/workloads/azure-resourcemanager-workloads/pom.xml @@ -50,12 +50,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0 com.azure.resourcemanager @@ -78,13 +78,13 @@ com.azure azure-core-test - 1.24.2 + 1.25.0 test com.azure azure-identity - 1.12.0 + 1.12.1 test diff --git a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/pom.xml b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/pom.xml index bb2fd98069f94..e34564edef9c3 100644 --- a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/pom.xml +++ b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/pom.xml @@ -51,12 +51,12 @@ com.azure azure-core - 1.48.0 + 1.49.0 com.azure azure-core-management - 1.13.0 + 1.14.0